<?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\ActivityBundle\Tests\Export\Filter\PersonsFilterTest;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\PersonBundle\Form\Type\PickPersonDynamicType;
use Chill\PersonBundle\Templating\Entity\PersonRenderInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @see PersonsFilterTest
 */
final readonly class PersonsFilter implements FilterInterface
{
    private const PREFIX = 'act_persons_filter';

    public function __construct(private PersonRenderInterface $personRender) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $p = self::PREFIX;

        $orX = $qb->expr()->orX();

        foreach (array_values($data['accepted_persons']) as $key => $person) {
            $orX->add($qb->expr()->isMemberOf(":{$p}_p_{$key}", 'activity.persons'));
            $qb->setParameter(":{$p}_p_{$key}", $person);
        }

        $qb->andWhere($orX);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_persons', PickPersonDynamicType::class, [
            'multiple' => true,
            'label' => 'export.filter.activity.by_persons.persons taking part on the activity',
        ]);
    }

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        $users = [];

        foreach ($data['accepted_persons'] as $u) {
            $users[] = $this->personRender->renderString($u, []);
        }

        return ['export.filter.activity.by_persons.Filtered activity by persons: only %persons%', [
            '%persons%' => implode(', ', $users),
        ]];
    }

    public function getTitle(): string
    {
        return 'export.filter.activity.by_persons.Filter activity by persons';
    }
}
