<?php

namespace AutoAdmin\Bundle\DependencyInjection;

use AutoAdmin\Bundle\Admin\Controller\Admin\AdminControllerInterface;
use AutoAdmin\Bundle\Admin\DependencyInjection\Configuration\ConfigurationDefault;
use AutoAdmin\Bundle\Cache\Entity\CacheRule;
use AutoAdmin\Bundle\Content\Breadcrumbs\Generator\BreadcrumbsGeneratorInterface;
use AutoAdmin\Bundle\Content\Configuration\ConfigBuilder as ContentConfigBuilder;
use AutoAdmin\Bundle\Content\Controller\AbstractContentController;
use AutoAdmin\Bundle\Content\Doctrine\StringFunctions\FindInSet;
use AutoAdmin\Bundle\Content\Doctrine\StringFunctions\GroupConcat;
use AutoAdmin\Bundle\Content\Doctrine\StringFunctions\Replace;
use AutoAdmin\Bundle\Content\Entity\Domain;
use AutoAdmin\Bundle\Content\Entity\Locale;
use AutoAdmin\Bundle\Content\Entity\Site;
use AutoAdmin\Bundle\Content\Logger\LoggerInterface;
use AutoAdmin\Bundle\Content\Repository\AbstractContentRepository;
use AutoAdmin\Bundle\Content\Repository\AbstractTranslatableContentRepository;
use AutoAdmin\Bundle\Content\Routing\ContentAutoRouterInterface;
use AutoAdmin\Bundle\DependencyInjection\Configuration\Configuration;
use AutoAdmin\Bundle\DependencyInjection\Configuration\RawConfigurationFixer;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Extension\ConfigurationExtensionInterface;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class AutoAdminExtension extends Extension implements ConfigurationExtensionInterface, PrependExtensionInterface
{
    public function load(array $configs, ContainerBuilder $container)
    {
        // prepare and validate config files (mainly class/slugs)
        $configs = (new RawConfigurationFixer())->fixRawConfigs($configs);

        $configs = $this->mergeDefaultActions($configs);

        $config = $this->processConfiguration((new Configuration()), $configs);

        $processedConfig = (new ContentConfigBuilder())->build($config);

        $processedConfig = $this->processConfiguration((new Configuration()), [$processedConfig]);

        $container->setParameter('aa_cache.config', $processedConfig['cache'] ?? []);
        $container->setParameter('aa_content.config', $processedConfig['content'] ?? []);
        $container->setParameter('aa_admin_file_config', $processedConfig['admin'] ?? []);
        $container->setParameter('aa_media_config', $processedConfig['media'] ?? []);
        $container->setParameter('aa_log.config', $processedConfig['log'] ?? []);

        $this->loadBrickBuilder($config, $container);
        $this->loadCore($config, $container);
        $this->loadMedia($config, $container);
        $this->loadSeo($config, $container);
        $this->loadContent($config, $container);
        $this->loadAdmin($config, $container);
        $this->loadMenu($config, $container);
        $this->loadCache($config, $container);
        $this->loadLog($config, $container);
    }

    protected function loadAdmin(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Admin/Resources/config'));
        $loader->load('services.yaml');
        $loader->load('controllers.yaml');
        $loader->load('config.yaml');
        $loader->load('form.yaml');
        $loader->load('twig.yaml');

        $container->registerForAutoconfiguration(AdminControllerInterface::class)
            ->addTag('aa_admin.controller', ['priority' => -100]);

        $container->registerForAutoconfiguration(AbstractContentRepository::class)
            ->addTag('aa_content.repository', ['priority' => 100]);
        $container->registerForAutoconfiguration(AbstractTranslatableContentRepository::class)
            ->addTag('aa_content.repository', ['priority' => 100]);
    }

    protected function loadBrickBuilder(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../BrickBuilder/Resources/config'));
        $loader->load('services.yaml');
        $loader->load('bricks.yaml');
    }

    protected function loadContent(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Content/Resources/config'));
        $loader->load('services.yaml');
        $loader->load('translation.yaml');
        $container->registerForAutoconfiguration(ContentAutoRouterInterface::class)
            ->addTag('aa_content.auto_router', ['priority' => 0]);

        // tag services extending this class
        $container->registerForAutoconfiguration(AbstractContentController::class)
            ->addTag('content.controller', ['priority' => 100]);

        $container->registerForAutoconfiguration(LoggerInterface::class)
            ->addTag('aa_content.logger', ['priority' => 0]);

        $container->registerForAutoconfiguration(BreadcrumbsGeneratorInterface::class)
            ->addTag('aa_content.breadcrumbs_generator', ['priority' => 0]);
    }

    protected function loadCore(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Core/Resources/config'));
        $loader->load('services.yaml');

        // 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);
            }
        }
    }

    protected function loadMedia(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Media/Resources/config'));
        $loader->load('services.yaml');
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Media/Resources/config'));
        $loader->load('services.yaml');
    }

    protected function loadMenu(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Menu/Resources/config'));
        $loader->load('services.yaml');
    }

    protected function loadSeo(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Seo/Resources/config'));
        $loader->load('services.yaml');
    }

    protected function loadCache(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Cache/Resources/config'));
        $loader->load('services.yaml');
    }

    protected function loadLog(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Log/Resources/config'));
        $loader->load('services.yaml');
    }

    public function getConfiguration(array $config, ContainerBuilder $container)
    {
        return new Configuration();
    }

    public function prepend(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('framework', [
            'translator' => [
                'paths' => [
                    __DIR__.'/../../src/Admin/Resources/translations',
                    __DIR__.'/../../src/BrickBuilder/Resources/translations',
                    __DIR__.'/../../src/Content/Resources/translations',
                    __DIR__.'/../../src/Seo/Resources/translations',
                    __DIR__.'/../../src/Menu/Resources/translations',
                    __DIR__.'/../../src/Media/Resources/translations',
                ],
            ],
        ]);

        $this->prependDoctrineEntities($container);
        $this->prependTwigPaths($container);
        $this->prependKnpMenu($container);

        $container->prependExtensionConfig('autoadmin', [
            'admin' => [
                'entities' => [
                    Site::class => [
                        'name' => 'Site',
                        'slug' => 'site',
                        'roles' => ['ROLE_SUPER_ADMIN'],
                        'list' => [
                            'fields' => [
                                ['property' => 'id', 'label' => "Identifiant"],
                                ['property' => 'title', 'label' => "Title"],
                                ['property' => 'domains', 'label' => "Domaines"],
                            ],
                        ],
                        'form' => [
                            'create' => [
                                ['property' => 'title', 'label' => "Titre"],
                                ['property' => 'domains', 'label' => "Domaines"],
                            ],
                            'update' => [
                                ['property' => 'title', 'label' => "Title"],
                                ['property' => 'domains', 'label' => "Domaines"],
                            ],
                        ],
                    ],
                    Domain::class => [
                        'name' => 'Domaine',
                        'slug' => 'domain',
                        'roles' => ['ROLE_SUPER_ADMIN'],
                        'list' => [
                            'fields' => [
                                ['property' => 'id', 'label' => "Identifiant"],
                                ['property' => 'domain', 'label' => "Domaine"],
                                ['property' => 'locales', 'label' => "Langues"],
                            ],
                            'form' => [
                                'create' => [
                                    ['property' => 'domain', 'label' => "Domaine"],
                                    ['property' => 'locales', 'label' => "Langues"],
                                ],
                                'update' => [
                                    ['property' => 'domain', 'label' => "Domaine"],
                                    ['property' => 'locales', 'label' => "Langues"],
                                ],
                            ],
                        ],
                    ],
                    Locale::class => [
                        'name' => 'Langue',
                        'slug' => 'locale',
                        'roles' => ['ROLE_SUPER_ADMIN'],
                        'list' => [
                            'fields' => [
                                ['property' => 'id', 'label' => "Identifiant"],
                                ['property' => 'code', 'label' => "Code"],
                            ],
                            'form' => [
                                'create' => [
                                    ['property' => 'code', 'label' => "Code"],
                                ],
                                'update' => [
                                    ['property' => 'code', 'label' => "Code"],
                                ],
                            ],
                        ],
                    ],
                    CacheRule::class => [
                        'name' => 'Règles de cache',
                        'slug' => 'cache-rule',
                        'roles' => ['ROLE_SUPER_ADMIN'],
                        'controller' => 'AutoAdmin\Bundle\Admin\Controller\Admin\CacheRuleController',
                        'list' => [
                            'fields' => [
                                ['property' => 'id', 'label' => 'Identifiant'],
                                ['property' => 'pattern', 'label' => 'Pattern'],
                                ['property' => 'isExcluded', 'label' => 'Exclure'],
                                ['property' => 'exactMatch', 'label' => 'Exact match'],
                            ],
                            'form' => [
                                'create' => [
                                    ['property' => 'pattern', 'label' => 'Pattern'],
                                    ['property' => 'isExcluded', 'label' => 'Exclure'],
                                    ['property' => 'exactMatch', 'label' => 'Exact match'],
                                ],
                                'update' => [
                                    ['property' => 'pattern', 'label' => 'Pattern'],
                                    ['property' => 'isExcluded', 'label' => 'Exclure'],
                                    ['property' => 'exactMatch', 'label' => 'Exact match'],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
            'content' => [

            ],
            'cache' => [
                'enabled' => false,
                'clear_on_flush' => true,
                'excluded_entities' => [],
            ],
            'log' => [

            ],
        ]);

        $this->prependMonolog($container);
    }

    private function prependMonolog(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('monolog', [
            'handlers' => [
                'aa_logtail' => [
                    'type' => 'service',
                    'id' => 'AutoAdmin\Bundle\Log\Monolog\Handler\LogtailHandler',
                ],
            ],
        ]);
    }

    private function prependDoctrineEntities(ContainerBuilder $container)
    {
        $mappings = [];

        // doctrine entity repos & entity mappings
        foreach (['Admin', 'Content', 'BrickBuilder', 'Seo', 'Menu', 'Cache', 'Media'] as $name) {
            $mappings['AutoAdminBundle'.$name] = [
                'is_bundle' => false,
                'type' => 'attribute',
                'dir' => __DIR__.'/../../src/'.$name.'/Entity',
                'prefix' => 'AutoAdmin\Bundle\\'.$name.'\\Entity',
                'alias' => 'AutoAdminBundle'.$name,
            ];
        }

        $container->prependExtensionConfig('doctrine', [
            'orm' => [
                'mappings' => $mappings,
                'dql' => [
                    'string_functions' => [
                        'REPLACE' => Replace::class,
                        'GROUP_CONCAT' => GroupConcat::class,
                        'FIND_IN_SET' => FindInSet::class,
                    ],
                ],
            ],
        ]);
    }

    private function prependTwigPaths(ContainerBuilder $container)
    {
        // twig directory paths
        $container->prependExtensionConfig(
            'twig',
            [
                'paths' => [
                    __DIR__.'/../../src/Content/Resources/views' => 'AutoAdminContent',
                    __DIR__.'/../../src/Admin/Resources/views' => 'AutoAdminAdmin',
                    __DIR__.'/../../src/BrickBuilder/Resources/views' => 'AutoAdminBrickBuilder',
                    __DIR__.'/../../src/Menu/Resources/views' => 'AutoAdminMenu',
                    __DIR__.'/../../src/Media/Resources/views' => 'AutoAdminMedia',
                ],
            ]
        );
    }

    private function prependKnpMenu(ContainerBuilder $container)
    {
        // menu default template
        $bundles = $container->getParameter('kernel.bundles');
        if (in_array('Knp\\Bundle\\MenuBundle\\KnpMenuBundle', $bundles, true)) {
            $config = [
                'twig' => [
                    // 'template' => 'KnpMenuBundle::menu.html.twig',
                    'template' => '@AutoAdminMenu/menu.html.twig',
                ],
            ];
            $container->prependExtensionConfig('knp_menu', $config);
        }
    }

    private function mergeDefaultActions(array $configs): array
    {
        foreach ($configs as $keyConfig => $config) {
            if (!isset($config['admin']['entities'])) {
                continue;
            }

            foreach ($config['admin']['entities'] as $classname => $entity) {
                if (!isset($entity['actions'])) {
                    continue;
                }

                foreach ($entity['actions'] as $keyAction => $action) {
                    $defaultAction = array_filter(
                        ConfigurationDefault::getDefaultActions(),
                        function ($defaultAction) use ($action) {
                            return $defaultAction['action'] === $action['action'];
                        }
                    );
                    $defaultAction = array_shift($defaultAction);
                    if (!$defaultAction) {
                        continue;
                    }

                    $configs[$keyConfig]['admin']['entities'][$classname]['actions'][$keyAction] = array_merge(
                        $defaultAction,
                        $action
                    );
                }
            }
        }

        return $configs;
    }
}
