<?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\ExportElementValidatedInterface;
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\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class AgeFilter implements ExportElementValidatedInterface, 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');

        $min = $data['min_age'] ?? 0;
        $max = $data['max_age'] ?? 150;
        $calc = $this->rollingDateConverter->convert($data['date_calc']);

        $minDate = $calc->sub(new \DateInterval('P'.$max.'Y'));
        $maxDate = $calc->sub(new \DateInterval('P'.$min.'Y'));

        $clause = $qb->expr()->andX(
            $qb->expr()->gte(
                'person.birthdate',
                ':min_date'
            ),
            $qb->expr()->lte(
                'person.birthdate',
                ':max_date'
            )
        );

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

        $qb->add('where', $where);
        $qb->setParameter('min_date', $minDate);
        $qb->setParameter('max_date', $maxDate);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('min_age', IntegerType::class, [
            'label' => 'Minimum age',
        ]);

        $builder->add('max_age', IntegerType::class, [
            'label' => 'Maximum age',
        ]);

        $builder->add('date_calc', PickRollingDateType::class, [
            'label' => 'Calculate age in relation to this date',
            'data' => new RollingDate(RollingDate::T_TODAY),
        ]);
    }

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return ['Filtered by person\'s age: '
        .'between %min_age% and %max_age%', [
            '%min_age%' => $data['min_age'],
            '%max_age%' => $data['max_age'],
        ], ];
    }

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

    public function validateForm($data, ExecutionContextInterface $context): void
    {
        $min = $data['min_age'];
        $max = $data['max_age'];

        if (
            (null !== $min && null !== $max)
            && $min >= $max
        ) {
            $context->buildViolation('The minimum age should be less than the maximum age.')
                ->addViolation();
        }
    }
}
