<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\DependencyInjection\Compiler;

use Ferienpass\AdminBundle\Form\Filter\AbstractFilterType;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

final class FilterSectionPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        foreach ($container->findTags() as $tag) {
            if (!str_starts_with($tag, 'ferienpass_admin.filter.') && 'ferienpass_admin.sub_filter' !== $tag) {
                continue;
            }

            foreach ($container->findTaggedServiceIds($tag) as $id => $tags) {
                $definition = $container->getDefinition($id);
                $class = $container->getParameterBag()->resolveValue($definition->getClass() ?: $id);

                if (!\is_string($class) || !is_subclass_of($class, AbstractFilterType::class)) {
                    continue;
                }

                foreach ($tags as $tagData) {
                    if (isset($tagData['section'])) {
                        $definition->addMethodCall('setSection', [$tagData['section']]);
                    }
                    if (isset($tagData['priority'])) {
                        $definition->addMethodCall('setPriority', [$tagData['priority']]);
                    }
                    if (isset($tagData['views'])) {
                        $definition->addMethodCall('setViews', [$tagData['views']]);
                    }
                }
            }
        }
    }
}
