<?php

namespace WordpressModels\DependencyInjection\CliCommandAttributes;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class WpCliCommandAttributesCompilerPass implements CompilerPassInterface
{

    public function process(ContainerBuilder $container)
    {
        if (!$container->has(WpCliCommandRegistry::class)) {
            return;
        }

        $definition = $container->findDefinition(WpCliCommandRegistry::class);

        $taggedServices = $container->findTaggedServiceIds('wp_cli.command');

        foreach ($taggedServices as $id => $tags) {
            $commandDefinition = $container->findDefinition($id);
            $baseName = '';

            // get the base command tag
            if ($commandDefinition->hasTag('wp_cli.command_base')) {
                $baseCommand = current($commandDefinition->getTag('wp_cli.command_base'));
                $baseName = $baseCommand['name'];
            }
            $serviceReference = new Reference($id);

            // add the command to the registry
            foreach ($tags as $attributes) {
                $method = $attributes['method'];
                $commandName = $method === '__invoke'
                    ? $baseName
                    : join(' ', array_filter([$baseName, $attributes['name']]));

                $definition->addMethodCall('addCommand', [
                    $commandName,
                    [$serviceReference, $method],
                    $attributes['args']
                ]);
            }
        }
    }
}