<?php

namespace KupShop\AdminBundle\DependencyInjection\Compiler;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\AdminBundle\Util\WindowTabLocator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

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

        $locator = $container->findDefinition(WindowTabLocator::class);

        $services = $container->findTaggedServiceIds('kupshop.admin.window_tab');

        $locatableServices = [];
        $servicesByTypes = [];
        foreach ($services as $id => $tags) {
            /** @var WindowTab $class */
            $class = $container->findDefinition($id)->getClass();
            if (!$class::isAllowed()) {
                continue;
            }

            $locatableServices[$id] = new Reference($id);

            $types = $class::getTypes();
            foreach ($types as $type => $priority) {
                $servicesByTypes[$type][$id] = $priority;
            }
        }

        // sort by priority
        foreach ($servicesByTypes as &$services) {
            arsort($services);
        }

        $locator->addArgument(ServiceLocatorTagPass::register($container, $locatableServices));
        $locator->addArgument($servicesByTypes);
    }
}
