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

use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\MaritalStatus;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Repository\MaritalStatusRepositoryInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

final readonly class MaritalStatusFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(private TranslatableStringHelper $translatableStringHelper, private MaritalStatusRepositoryInterface $maritalStatusRepository) {}

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

    public function alterQuery(\Doctrine\ORM\QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $qb->andWhere(
            $qb->expr()->in('person.maritalStatus', ':maritalStatus')
        );
        $qb->setParameter('maritalStatus', $data['maritalStatus']);
    }

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

    public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder): void
    {
        $builder->add('maritalStatus', EntityType::class, [
            'class' => MaritalStatus::class,
            'choice_label' => fn (MaritalStatus $ms) => $this->translatableStringHelper->localize(
                $ms->getName()
            ),
            'multiple' => true,
            'expanded' => true,
        ]);
    }

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return ['Filtered by person\'s marital status'];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'Filter by person\'s marital status';
    }
}
