<?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\PickUserOrMeDynamicType;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use Chill\MainBundle\Templating\Entity\UserRender;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

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

    public function __construct(private UserRender $userRender, private UserRepositoryInterface $userRepository) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $orX = $qb->expr()->orX();

        foreach ($this->userOrMe($data['accepted_users'], $exportGenerationContext) as $key => $user) {
            $orX->add($qb->expr()->isMemberOf(':activity_users_filter_u'.$key, 'activity.users'));
            $qb->setParameter('activity_users_filter_u'.$key, $user);
        }

        $qb->andWhere($orX);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_users', PickUserOrMeDynamicType::class, [
            'multiple' => true,
            'label' => 'Users',
        ]);
    }

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

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

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_users' => $this->denormalizeUserOrMe($formData['accepted_users'], $this->userRepository)];
    }

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

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

        foreach ($this->userOrMe($data['accepted_users'], $context) as $u) {
            $users[] = $this->userRender->renderString($u, []);
        }

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

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