<?php

namespace KupShop\AdminBundle\DependencyInjection\Compiler;

use KupShop\AdminBundle\AdminRegister\AdminRegisterLocator;
use KupShop\AdminBundle\AdminRegister\IAdminRegisterDynamic;
use KupShop\AdminBundle\AdminRegister\IAdminRegisterStatic;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class AdminRegisterPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->has(AdminRegisterLocator::class)) {
            return;
        }

        $locator = $container->findDefinition(AdminRegisterLocator::class);
        $services = $container->findTaggedServiceIds('kupshop.admin.register');

        $permissions = [];
        $menu = [];
        $dynamicRegistrations = [];
        foreach ($services as $id => $tags) {
            $def = $container->findDefinition($id);
            $instanceof = class_implements($def->getClass());
            if (in_array(IAdminRegisterDynamic::class, $instanceof)) {
                $dynamicRegistrations[$def->getClass()] = new Reference($def->getClass());
            }
            if (in_array(IAdminRegisterStatic::class, $instanceof)) {
                /** @var IAdminRegisterStatic $class */
                $class = $def->getClass();
                foreach ($class::getPermissions() as $arr) {
                    $type = $arr['type'];
                    unset($arr['type']);
                    $permissions[$type] = $arr;
                }
                foreach ($class::getMenu() as $arr) {
                    $menu[$arr['menu']][] = $arr['item'];
                }
            }
        }

        $locator->addArgument($permissions);
        $locator->addArgument($menu);
        $locator->addArgument(ServiceLocatorTagPass::register($container, $dynamicRegistrations));
        $locator->addArgument(array_keys($dynamicRegistrations));
    }
}
