<?php

namespace KupShop\AutomationConfiguratorBundle\DependencyInjection\Compiler;

use KupShop\AutomationConfiguratorBundle\Util\AutomationConfiguratorLocator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

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

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

        $builderElements = $container->findTaggedServiceIds('kupshop.automationConfigurator.context');

        $fields = $container->findTaggedServiceIds('kupshop.automationConfigurator.field');
        $triggers = $container->findTaggedServiceIds('kupshop.automationConfigurator.trigger');
        $actions = $container->findTaggedServiceIds('kupshop.automationConfigurator.action');
        $groups = $container->findTaggedServiceIds('kupshop.automationConfigurator.group');
        $providers = $container->findTaggedServiceIds('kupshop.automationConfigurator.provider');

        $triggersContextNames = [];
        $contextServices = [];

        foreach ($builderElements as $id => $tags) {
            foreach ($tags as $tag) {
                $contextName = $tag['context'];
                if (!empty($fields[$id])) {
                    $contextServices['fields'][$contextName][] = $id;
                } elseif (!empty($triggers[$id])) {
                    $contextServices['triggers'][$contextName][] = $id;
                    $triggersContextNames[$id][] = $contextName;
                } elseif (!empty($actions[$id])) {
                    $contextServices['actions'][$contextName][] = $id;
                } elseif (!empty($groups[$id])) {
                    $contextServices['groups'][$contextName][] = $id;
                } elseif (!empty($providers[$id])) {
                    $contextServices['providers'][$contextName] = $id;
                }
            }
        }

        $locator->addArgument($triggersContextNames);
        $locator->addArgument($contextServices);
    }
}
