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

use Chill\EventBundle\Export\Declarations;
use Chill\EventBundle\Repository\EventTypeRepository;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class EventTypeAggregator implements AggregatorInterface
{
    final public const KEY = 'event_type_aggregator';

    public function __construct(protected EventTypeRepository $eventTypeRepository, protected TranslatableStringHelperInterface $translatableStringHelper) {}

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

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

        $qb->addSelect(sprintf('IDENTITY(event.type) AS %s', self::KEY));
        $qb->addGroupBy(self::KEY);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        // no form required for this aggregator
    }

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

    public function normalizeFormData(array $formData): array
    {
        return [];
    }

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

    public function getFormDefaultData(): array
    {
        return [];
    }

    public function getLabels($key, array $values, $data): callable
    {
        return function (int|string|null $value): string {
            if ('_header' === $value) {
                return 'Event type';
            }

            if (null === $value || '' === $value || null === $t = $this->eventTypeRepository->find($value)) {
                return '';
            }

            return $this->translatableStringHelper->localize($t->getName());
        };
    }

    public function getQueryKeys($data): array
    {
        return [self::KEY];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'Group by event type';
    }
}
