<?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\Aggregator\AccompanyingCourseAggregators;

use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final readonly class StepAggregator implements AggregatorInterface
{
    private const A = 'acpstephistories';

    private const P = 'acp_step_agg_date';

    public function __construct(private RollingDateConverterInterface $rollingDateConverter, private TranslatorInterface $translator) {}

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        if (!\in_array(self::A, $qb->getAllAliases(), true)) {
            $qb->leftJoin('acp.stepHistories', self::A);
        }

        $qb
            ->addSelect(self::A.'.step AS step_aggregator')
            ->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->isNull(self::A.'.step'),
                    $qb->expr()->andX(
                        $qb->expr()->lte(self::A.'.startDate', ':'.self::P),
                        $qb->expr()->orX(
                            $qb->expr()->isNull(self::A.'.endDate'),
                            $qb->expr()->gt(self::A.'.endDate', ':'.self::P)
                        )
                    )
                )
            )
            ->setParameter(self::P, $this->rollingDateConverter->convert($data['on_date']))
            ->addGroupBy('step_aggregator');
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('on_date', PickRollingDateType::class, []);
    }

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

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

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

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

    public function getLabels($key, array $values, $data): callable
    {
        return function ($value): string {
            switch ($value) {
                case AccompanyingPeriod::STEP_DRAFT:
                    return $this->translator->trans('course.draft');

                case AccompanyingPeriod::STEP_CONFIRMED:
                    return $this->translator->trans('course.confirmed');

                case AccompanyingPeriod::STEP_CLOSED:
                    return $this->translator->trans('course.closed');

                case AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_SHORT:
                    return $this->translator->trans('course.inactive_short');

                case AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_LONG:
                    return $this->translator->trans('course.inactive_long');

                case '_header':
                    return 'Step';

                case null:
                case '':
                    return '';

                default:
                    return $value;
            }
        };
    }

    public function getQueryKeys($data): array
    {
        return ['step_aggregator'];
    }

    public function getTitle(): string
    {
        return 'Group by step';
    }

    /*
     * TODO check if we need to add FilterInterface and DescribeAction Method to describe date filter ??
     *
    public function describeAction($data, $format = 'string')
    {
        return [
            "Filtered by actives courses: active on %ondate%", [
                '%ondate%' => $data['on_date']->format('d-m-Y')
            ]
        ];
    }
     */
}
