<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\DependencyInjection\CompilerPass;

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

/**
 * Add services taggued with  `name: chill.timeline` to
 * timeline_builder service definition.
 */
class TimelineCompilerClass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('chill_main.timeline_builder')) {
            throw new \LogicException('service chill_main.timeline_builder is not defined.');
        }

        $definition = $container->getDefinition(
            'chill_main.timeline_builder'
        );

        $taggedServices = $container->findTaggedServiceIds(
            'chill.timeline'
        );

        foreach ($taggedServices as $id => $tagAttributes) {
            foreach ($tagAttributes as $attributes) {
                if (!isset($attributes['context'])) {
                    throw new \LogicException("the 'context' attribute is missing in your service '{$id}' definition");
                }

                $definition->addMethodCall(
                    'addProvider',
                    [$attributes['context'], $id, new Reference($id)]
                );
            }
        }
    }
}
