<?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\PersonBundle\DependencyInjection\CompilerPass;

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

/**
 * Remove services which add AccompanyingPeriod to timeline if
 * accompanying_periods are set to `hidden`.
 */
class AccompanyingPeriodTimelineCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        // remove services when accompanying period are hidden
        if ('hidden' !== $container->getParameter('chill_person.accompanying_period')) {
            return;
        }

        $definitions = [
            'chill.person.timeline.accompanying_period_opening',
            'chill.person.timeline.accompanying_period_closing',
        ];

        foreach ($definitions as $definition) {
            $container
                ->removeDefinition($definition);
        }

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

        // we have to remove all methods call, and re-add them if not linked
        // to this service
        $calls = $definition->getMethodCalls();

        foreach ($calls as [$method, $arguments]) {
            if ('addProvider' !== $method) {
                continue;
            }

            $definition->removeMethodCall('addProvider');

            if (false === \in_array($arguments[1], $definitions, true)) {
                $definition->addMethodCall($method, $arguments);
            }
        }
    }
}
