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

use Chill\ActivityBundle\Entity\ActivityType;
use Chill\ActivityBundle\Export\Declarations;
use Chill\ActivityBundle\Repository\ActivityTypeRepositoryInterface;
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 ActivityTypeFilter implements ExportElementValidatedInterface, FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(
        protected TranslatableStringHelperInterface $translatableStringHelper,
        protected ActivityTypeRepositoryInterface $activityTypeRepository,
    ) {}

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

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

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

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('types', EntityType::class, [
            'choices' => $this->activityTypeRepository->findAllActive(),
            'class' => ActivityType::class,
            'choice_label' => fn (ActivityType $aty) => ($aty->hasCategory() ? $this->translatableStringHelper->localize($aty->getCategory()->getName()).' > ' : '')
            .
            $this->translatableStringHelper->localize($aty->getName()),
            'group_by' => function (ActivityType $type) {
                if (!$type->hasCategory()) {
                    return null;
                }

                return $this->translatableStringHelper->localize($type->getCategory()->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->activityTypeRepository)];
    }

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

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        // collect all the reasons'name used in this filter in one array
        $reasonsNames = array_map(
            fn (ActivityType $t): string => $this->translatableStringHelper->localize($t->getName()),
            $this->activityTypeRepository->findBy(['id' => $data['types'] instanceof \Doctrine\Common\Collections\Collection ? $data['types']->toArray() : $data['types']])
        );

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

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'Filter by activity 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();
        }
    }
}
