<?php

namespace idoit\Component\PlaceholderReplacer\Placeholder\Counter;

use idoit\Component\PlaceholderReplacer\Config;
use idoit\Component\PlaceholderReplacer\Placeholder\PlaceholderInterface;

class CounterNwithStart extends AbstractCounter
{
    use CounterTrait;

    /**
     * @var string
     */
    protected static string $pattern = "/%COUNTER\:(\d+)#(\d+)%/";

    /**
     * @param string $value
     * @param Config $config
     *
     * @return string
     */
    public function replacePlaceholder(string $value, Config $config): string
    {
        preg_match_all($this->getPattern(), $value, $matches);

        foreach ($matches[0] as $index => $search) {
            $startFrom = (int)$matches[1][$index];
            $length = (int)$matches[2][$index];
            $value = str_replace($search, str_pad(static::getCounter($search), $length, '0', STR_PAD_LEFT), $value);
            static::updateCounter($search);
        }

        return $value;
    }

    /**
     * @param string $value
     * @param Config $config
     *
     * @return void
     */
    public static function setCounters(string $value, Config $config)
    {
        preg_match_all(static::$pattern, $value, $matches);

        foreach ($matches[0] as $index => $search) {
            if (isset(self::$currentCounters[$search])) {
                continue;
            }
            self::$currentCounters[$search] = $matches[1][$index];
        }
    }
}
