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

use Chill\CalendarBundle\Export\Declarations;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Repository\LocationTypeRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class LocationTypeAggregator implements AggregatorInterface
{
    public function __construct(private LocationTypeRepository $locationTypeRepository, private TranslatableStringHelper $translatableStringHelper) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        if (!\in_array('calloc', $qb->getAllAliases(), true)) {
            $qb->join('cal.location', 'calloc');
        }

        $qb->addSelect('IDENTITY(calloc.locationType) as location_type_aggregator');
        $qb->addGroupBy('location_type_aggregator');
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        // no form
    }

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

    public function getLabels($key, array $values, $data): \Closure
    {
        return function ($value): string {
            if ('_header' === $value) {
                return 'Location type';
            }

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

            if (null === $j = $this->locationTypeRepository->find($value)) {
                return '';
            }

            return $this->translatableStringHelper->localize(
                $j->getTitle()
            );
        };
    }

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

    public function getTitle(): string
    {
        return 'Group calendars by location type';
    }
}
