<?php

namespace AutoAdmin\Bundle\Core\DependencyInjection;

use AutoAdmin\Bundle\Core\Slugger\Slugger;
use AutoAdmin\Bundle\Core\Twig\SluggerExtension;
use Cocur\Slugify\Bridge\Symfony\Configuration;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\HttpKernel\Kernel;

class AutoAdminCoreExtension extends Extension
{
    /**
     * TODO: only use a subset of general config for slugger
     * TODO: ex:
     * TODO:
     * TODO: aa_core:
     * TODO:     slugger: ~ // <- this part
     * TODO:
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yaml');

        // slugger
        $this->configureSlugger($config, $container);

        // set defaults for languages
        $locales = ['fr', 'en'];
        $defaults = [
            'locales' => $locales,
            'locales_pattern' => sprintf('(%s)', implode('|', $locales)),
            'default_locale' => 'fr',
        ];
        foreach ($defaults as $name => $value) {
            try {
                $container->getParameter($name);
            } catch (ParameterNotFoundException $exception) {
                $container->setParameter($name, $value);
            }
        }

    }

    public function configureSlugger(array $config, ContainerBuilder $container)
    {
        if (empty($config['rulesets'])) {
            unset($config['rulesets']);
        }

        // Extract slugify arguments from config
        $slugifyArguments = array_intersect_key($config, array_flip(['lowercase', 'separator', 'regexp', 'rulesets']));

        $container->setDefinition('aa_slugger', new Definition(Slugger::class, [$slugifyArguments]));
        $container
            ->setDefinition(
                'aa_slugger.twig.slugify',
                new Definition(SluggerExtension::class, [new Reference('aa_slugger')])
            )
            ->addTag('twig.extension')
            ->setPublic(false);
        $container->setAlias('slugger', 'aa_slugger');

        // for symfony versions > 3.3
        if (Kernel::VERSION_ID > 30300) {
            $container->setAlias(Slugger::class, 'aa_slugger');
        }
    }
}
