<?php

namespace KupShop\ContentBundle\DependencyInjection\Compiler;

use KupShop\ContentBundle\Page\BasePage;
use KupShop\ContentBundle\Util\PageLocator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

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

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

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

        $locatableServices = [];
        $servicesByTypes = [];
        foreach ($services as $id => $tags) {
            /** @var BasePage $class */
            $class = $container->findDefinition($id)->getClass();

            $locatableServices[$id] = new Reference($id);
            $servicesByTypes[$class::getType()] = ['priority' => $class::getPriority(), 'class' => $id];
        }

        // sort by priority
        arsort($servicesByTypes);

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