<?php

namespace KupShop\KupShopBundle\DependencyInjection\Compiler;

use KupShop\KupShopBundle\Email\EmailInterface;
use KupShop\KupShopBundle\Util\Mail\EmailLocator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

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

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

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

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

            if ($class::isAllowed()) {
                $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);
    }
}
