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

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

class DateAggregator implements AggregatorInterface
{
    private const CHOICES = [
        'by month' => 'month',
        'by week' => 'week',
        '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
    {
        $order = null;

        switch ($data['frequency']) {
            case 'month':
                $fmt = 'YYYY-MM';

                break;

            case 'week':
                $fmt = 'YYYY-IW';

                break;

            case 'year':
                $fmt = 'YYYY';
                $order = 'DESC';

                break; // order DESC does not works !

            default:
                throw new \RuntimeException(sprintf("The frequency data '%s' is invalid.", $data['frequency']));
        }

        $qb->addSelect(sprintf("TO_CHAR(activity.date, '%s') AS date_aggregator", $fmt));
        $qb->addGroupBy('date_aggregator');
        $qb->addOrderBy('date_aggregator', $order);
    }

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

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

    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) use ($data): string {
            if ('_header' === $value) {
                return 'by '.$data['frequency'];
            }

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

            return match ($data['frequency']) {
                default => $value,
            };
        };
    }

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

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