<?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\Export\Declarations;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class EmergencyFilter implements FilterInterface
{
    private const CHOICES = [
        'activity is emergency' => 'true',
        'activity is not emergency' => 'false',
    ];

    private const DEFAULT_CHOICE = 'false';

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

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $where = $qb->getDQLPart('where');

        $clause = $qb->expr()->eq('activity.emergency', ':emergency');

        if ($where instanceof Andx) {
            $where->add($clause);
        } else {
            $where = $qb->expr()->andX($clause);
        }

        $qb->add('where', $where);
        $qb->setParameter('emergency', $data['accepted_emergency']);
    }

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

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

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

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

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

    public function getFormDefaultData(): array
    {
        return ['accepted_emergency' => self::DEFAULT_CHOICE];
    }

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

    public function getTitle(): string
    {
        return 'Filter activity by emergency';
    }
}
