<?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\RoleRepository;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class RoleAggregator implements AggregatorInterface
{
    final public const KEY = 'part_role_aggregator';

    public function __construct(protected RoleRepository $roleRepository, protected TranslatableStringHelperInterface $translatableStringHelper) {}

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

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

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

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

    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 'Participant role';
            }

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

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

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

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