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

use Chill\MainBundle\Export\AggregatorInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;

final class ByEndDateAggregator implements AggregatorInterface
{
    private const CHOICES = [
        'by week' => 'week',
        'by month' => 'month',
        'by year' => 'year',
    ];

    private const DEFAULT_CHOICE = 'year';

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        $fmt = match ($data['frequency']) {
            'week' => 'YYYY-IW',
            'month' => 'YYYY-MM',
            'year' => 'YYYY',
            default => throw new \LogicException(sprintf("The frequency data '%s' is invalid.", $data['frequency'])),
        };

        $qb->addSelect(sprintf("TO_CHAR(workeval.endDate, '%s') AS eval_by_end_date_aggregator", $fmt));
        $qb->addGroupBy(' eval_by_end_date_aggregator');
        $qb->addOrderBy(' eval_by_end_date_aggregator', 'ASC');
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('frequency', 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 ['frequency' => $formData['frequency']];
    }

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

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

    public function getLabels($key, array $values, $data): callable
    {
        return static function ($value): string {
            if ('_header' === $value) {
                return 'export.aggregator.eval.by_end_date.End date period';
            }

            if (null === $value) {
                return '';
            }

            return $value;
        };
    }

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

    public function getTitle(): string
    {
        return 'export.aggregator.eval.by_end_date.Group by end date evaluations';
    }
}
