<?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\EvaluationFilters;

use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class MaxDateFilter implements FilterInterface
{
    private const MAXDATE_CHOICES = [
        'maxdate is specified' => true,
        'maxdate is not specified' => false,
    ];

    public function __construct(private readonly TranslatorInterface $translator) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        if (true === $data['maxdate']) {
            $clause = $qb->expr()->isNotNull('workeval.maxDate');
        } else {
            $clause = $qb->expr()->isNull('workeval.maxDate');
        }

        $qb->andWhere($clause);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('maxdate', ChoiceType::class, [
            'choices' => self::MAXDATE_CHOICES,
            'multiple' => false,
            'expanded' => true,
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['maxdate' => $formData['maxdate']];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['maxdate' => $formData['maxdate']];
    }

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return ['Filtered by maxdate: only %choice%', [
            '%choice%' => $this->translator->trans(
                $data['maxdate'] ? 'maxdate is specified' : 'maxdate is not specified'
            ),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter evaluations by maxdate mention';
    }
}
