<?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\EventBundle\Export\Filter;

use Chill\EventBundle\Entity\Role;
use Chill\EventBundle\Export\Declarations;
use Chill\EventBundle\Repository\RoleRepository;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class RoleFilter implements ExportElementValidatedInterface, FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(
        protected TranslatableStringHelperInterface $translatableStringHelper,
        protected RoleRepository $roleRepository,
    ) {}

    public function addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $clause = $qb->expr()->in('event_part.role', ':selected_part_roles');

        $qb->andWhere($clause);
        $qb->setParameter('selected_part_roles', $data['part_roles']);
    }

    public function applyOn(): string
    {
        return Declarations::EVENT_PARTICIPANTS;
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('part_roles', EntityType::class, [
            'choices' => $this->roleRepository->findAllActive(),
            'class' => Role::class,
            'choice_label' => fn (Role $r) => $this->translatableStringHelper->localize($r->getName()),
            'multiple' => true,
            'expanded' => false,
            'attr' => [
                'class' => 'select2',
            ],
        ]);
    }

    public function getNormalizationVersion(): int
    {
        return 1;
    }

    public function normalizeFormData(array $formData): array
    {
        return ['part_roles' => $this->normalizeDoctrineEntity($formData['part_roles'])];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['part_roles' => $this->denormalizeDoctrineEntity($formData['part_roles'], $this->roleRepository)];
    }

    public function getFormDefaultData(): array
    {
        return [];
    }

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        $roleNames = array_map(
            fn (Role $r): string => $this->translatableStringHelper->localize($r->getName()),
            $this->roleRepository->findBy(['id' => $data['part_roles'] instanceof \Doctrine\Common\Collections\Collection ? $data['part_roles']->toArray() : $data['part_roles']])
        );

        return ['Filtered by participant roles: only %list%', [
            '%list%' => implode(', ', $roleNames),
        ]];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'Filter by participant roles';
    }

    public function validateForm($data, ExecutionContextInterface $context): void
    {
        if (null === $data['part_roles'] || 0 === \count($data['part_roles'])) {
            $context
                ->buildViolation('At least one role must be chosen')
                ->addViolation();
        }
    }
}
