<?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\EventType;
use Chill\EventBundle\Export\Declarations;
use Chill\EventBundle\Repository\EventTypeRepository;
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 EventTypeFilter implements ExportElementValidatedInterface, FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(
        protected TranslatableStringHelperInterface $translatableStringHelper,
        protected EventTypeRepository $eventTypeRepository,
    ) {}

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

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

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

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

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

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

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

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

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

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

        return ['Filtered by event type: only %list%', [
            '%list%' => implode(', ', $typeNames),
        ]];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'Filtered by event type';
    }

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