<?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\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;

class DeadOrAliveFilter implements FilterInterface
{
    public function __construct(private readonly RollingDateConverterInterface $rollingDateConverter) {}

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

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

        $personState = $data['person_state'];
        $calc = $this->rollingDateConverter->convert($data['date_calc']);

        if ('alive' === $personState) {
            $clause = $qb->expr()->orX(
                $qb->expr()->andX(
                    $qb->expr()->isNull('person.deathdate'),
                    $qb->expr()->lte(
                        'person.birthdate',
                        ':date_calc'
                    )
                ),
                $qb->expr()->andX(
                    $qb->expr()->isNotNull('person.deathdate'),
                    $qb->expr()->gt(
                        'person.deathdate',
                        ':date_calc'
                    ),
                    $qb->expr()->lte(
                        'person.birthdate',
                        ':date_calc'
                    )
                )
            );
        } else {
            $clause = $qb->expr()->andX(
                $qb->expr()->isNotNull('person.deathdate'),
                $qb->expr()->lte(
                    'person.deathdate',
                    ':date_calc'
                )
            );
        }

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

        $qb->add('where', $where);
        $qb->setParameter('date_calc', $calc);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('person_state', ChoiceType::class, [
            'choices' => [
                'Alive' => 'alive',
                'Deceased' => 'deceased',
            ],
            'multiple' => false,
            'expanded' => true,
        ]);

        $builder->add('date_calc', PickRollingDateType::class, [
            'label' => 'Filter in relation to this date',
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['person_state' => $formData['person_state'], 'date_calc' => $formData['date_calc']->normalize()];
    }

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

    public function getFormDefaultData(): array
    {
        return ['date_calc' => new RollingDate(RollingDate::T_TODAY)];
    }

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return ['Filtered by a state of %deadOrAlive%: '
        .'at this date %date_calc%', [
            '%date_calc%' => $this->rollingDateConverter->convert($data['date_calc'])->format('d-m-Y'),
            '%deadOrAlive%' => $data['person_state'],
        ], ];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return "Filter by person's that are alive or have deceased at a certain date";
    }
}
