<?php

namespace External\MSSQLBundle\DependencyInjection\Compiler;

use External\MSSQLBundle\Synchronizers\SynchronizerInterface;
use External\MSSQLBundle\Util\SynchronizerLocator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class SynchronizerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        // always first check if the primary service is defined
        if (!$container->has(SynchronizerLocator::class)) {
            return;
        }

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

        // find all service IDs with the vario.synchronizer tag
        $taggedServices = $container->findTaggedServiceIds('money.synchronizer');

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

            if (!$class::getType()) {
                continue;
            }

            $locatableServices[$id] = new Reference($id);
            $servicesByTypes[$class::getType()] = $id;
        }

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