<?php

namespace Ingot\Normalizer;

use Symfony\Component\Config\FileLocatorInterface;

class NetGroupNormalizer implements \Tacker\Normalizer
{
    private $locator;
    private $file;
    private $loaded = array();

    /**
     * @param FileLocatorInterface $locator
     * @param string $file
     */
    public function __construct($locator, $file = 'pco.json')
    {
        $this->locator = $locator;
        $this->file = $file;
    }

    public function normalize($value)
    {
        $this->load();

        if (preg_match('{^#([a-zA-Z0-9_.]+)#$}', $value, $match)) {
            return $this->get($match[1], $match[0]);
        }

        $result = preg_replace_callback('{##|#([a-zA-Z0-9_.]+)#}', [$this, 'callback'], $value, -1, $count);

        return $count ? $result : $value;
    }

    protected function callback($matches)
    {
        return isset($matches[1]) ? $this->get($matches[1], $matches[0]) : $matches[0];
    }

    private function get($path, $default)
    {
        $token = strtok($path, '.');
        $current = $this->loaded;

        if (isset($current[$path])) {
            return $current[$path];
        }

        while ($token !== false) {
            if (!isset($current[$token])) {
                return $default;
            }


            $current = $current[$token];
            $token = strtok('.');
        }

        return $current;
    }

    private function load()
    {
        if ($this->loaded) {
            return;
        }

        if ($resource = $this->locator->locate($this->file)) {
            $this->loaded = json_decode(file_get_contents($resource), true);
        }
    }
}
