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

use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Chill\MainBundle\Repository\CountryRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\MainBundle\Util\CountriesInfo;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final readonly class NationalityAggregator implements AggregatorInterface, ExportElementValidatedInterface
{
    public function __construct(private CountryRepository $countriesRepository, private TranslatableStringHelper $translatableStringHelper, private TranslatorInterface $translator) {}

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        // add a clause in select part
        if ('country' === $data['group_by_level']) {
            $qb->addSelect('nationality.countryCode as nationality_aggregator');
        } elseif ('continent' === $data['group_by_level']) {
            $clause = 'CASE '
                    .'WHEN nationality.countryCode IN(:africa_codes) THEN \'AF\' '
                    .'WHEN nationality.countryCode IN(:asia_codes) THEN \'AS\' '
                    .'WHEN nationality.countryCode IN(:europe_codes) THEN \'EU\' '
                    .'WHEN nationality.countryCode IN(:north_america_codes) THEN \'NA\' '
                    .'WHEN nationality.countryCode IN(:south_america_codes) THEN \'SA\' '
                    .'WHEN nationality.countryCode IN(:oceania_codes) THEN \'OC\' '
                    .'WHEN nationality.countryCode IN(:antartica_codes) THEN \'AN\' '
                    .'ELSE \'\' '
                    .'END as nationality_aggregator ';
            $qb->addSelect($clause);
            $params =
                    [
                        'africa_codes' => CountriesInfo::getCountriesCodeByContinent('AF'),
                        'asia_codes' => CountriesInfo::getCountriesCodeByContinent('AS'),
                        'europe_codes' => CountriesInfo::getCountriesCodeByContinent('EU'),
                        'north_america_codes' => CountriesInfo::getCountriesCodeByContinent('NA'),
                        'south_america_codes' => CountriesInfo::getCountriesCodeByContinent('SA'),
                        'oceania_codes' => CountriesInfo::getCountriesCodeByContinent('OC'),
                        'antartica_codes' => CountriesInfo::getCountriesCodeByContinent('AN'),
                    ];

            foreach ($params as $k => $v) {
                $qb->setParameter($k, $v);
            }
        } else {
            throw new \LogicException("The group_by_level '".$data['group_by_level'].' is not known.');
        }

        $qb->leftJoin('person.nationality', 'nationality');
        $qb->addGroupBy('nationality_aggregator');
    }

    public function applyOn(): string
    {
        return 'person';
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('group_by_level', ChoiceType::class, [
            'choices' => [
                'Group by continents' => 'continent',
                'Group by country' => 'country',
            ],
            'expanded' => true,
            'multiple' => false,
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['group_by_level' => $formData['group_by_level']];
    }

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

    public function getFormDefaultData(): array
    {
        return [
            'group_by_level' => 'country',
        ];
    }

    public function getLabels($key, array $values, $data): callable
    {
        $labels = [];

        if ('country' === $data['group_by_level']) {
            $qb = $this->countriesRepository->createQueryBuilder('c');

            $countries = $qb
                ->andWhere($qb->expr()->in('c.countryCode', ':countries'))
                ->setParameter('countries', $values)
                ->getQuery()
                ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);

            // initialize array and add blank key for null values
            $labels = [
                '' => $this->translator->trans('without data'),
                '_header' => $this->translator->trans('Nationality'),
            ];

            foreach ($countries as $row) {
                $labels[$row['c_countryCode']] = $this->translatableStringHelper->localize($row['c_name']);
            }
        }

        if ('continent' === $data['group_by_level']) {
            $labels = [
                'EU' => $this->translator->trans('Europe'),
                'AS' => $this->translator->trans('Asia'),
                'AN' => $this->translator->trans('Antartica'),
                'AF' => $this->translator->trans('Africa'),
                'SA' => $this->translator->trans('South America'),
                'NA' => $this->translator->trans('North America'),
                'OC' => $this->translator->trans('Oceania'),
                '' => $this->translator->trans('without data'),
                '_header' => $this->translator->trans('Continent'),
            ];
        }

        return static fn ($value): string => $labels[$value];
    }

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

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

    public function validateForm($data, ExecutionContextInterface $context): void
    {
        if (null === $data['group_by_level']) {
            $context->buildViolation('You should select an option')
                ->addViolation();
        }
    }
}
