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

use Chill\ActivityBundle\Export\Declarations;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickUserLocationType;
use Chill\MainBundle\Repository\LocationRepository;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class LocationFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(
        private LocationRepository $locationRepository,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $qb->andWhere(
            $qb->expr()->in('activity.location', ':location')
        );

        $qb->setParameter('location', $data['accepted_location']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_location', PickUserLocationType::class, [
            'multiple' => true,
            'label' => 'pick location',
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['accepted_location' => $this->normalizeDoctrineEntity($formData['accepted_location'])];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_location' => $this->denormalizeDoctrineEntity($formData['accepted_location'], $this->locationRepository)];
    }

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $locations = [];

        foreach ($data['accepted_location'] as $location) {
            $locations[] = $location->getName();
        }

        return ['Filtered activity by location: only %locations%', [
            '%locations%' => implode(', ', $locations),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter activity by location';
    }
}
