<?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\EventBundle\Form\Type;

use Chill\EventBundle\Entity\Event;
use Chill\EventBundle\Form\ChoiceLoader\EventChoiceLoader;
use Chill\EventBundle\Repository\EventRepository;
use Chill\EventBundle\Search\EventSearch;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Class PickEventType.
 */
final class PickEventType extends AbstractType
{
    /**
     * PickEventType constructor.
     */
    public function __construct(
        private readonly EventRepository $eventRepository,
        private readonly AuthorizationHelperInterface $authorizationHelper,
        private readonly UrlGeneratorInterface $urlGenerator,
        private readonly TranslatorInterface $translator,
        private readonly Security $security,
    ) {}

    public function buildView(\Symfony\Component\Form\FormView $view, \Symfony\Component\Form\FormInterface $form, array $options)
    {
        $view->vars['attr']['data-person-picker'] = true;
        $view->vars['attr']['data-select-interactive-loading'] = true;
        $view->vars['attr']['data-search-url'] = $this->urlGenerator
            ->generate('chill_main_search', ['name' => EventSearch::NAME, '_format' => 'json']);
        $view->vars['attr']['data-placeholder'] = $this->translator->trans($options['placeholder']);
        $view->vars['attr']['data-no-results-label'] = $this->translator->trans('select2.no_results');
        $view->vars['attr']['data-error-load-label'] = $this->translator->trans('select2.error_loading');
        $view->vars['attr']['data-searching-label'] = $this->translator->trans('select2.searching');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        // add the possibles options for this type
        $resolver
            ->setDefined('centers')
            ->addAllowedTypes('centers', ['array', Center::class, 'null'])
            ->setDefault('centers', null);
        $resolver
            ->setDefined('role')
            ->addAllowedTypes('role', ['string', 'null'])
            ->setDefault('role', null);

        // add the default options
        $resolver->setDefaults([
            'class' => Event::class,
            'choice_label' => static fn (Event $e) => $e->getDate()->format('d/m/Y, H:i').' → '.
                    // $e->getType()->getName()['fr'] . ':  ' .    // display the type of event
                    $e->getName(),
            'placeholder' => 'Pick an event',
            'attr' => ['class' => 'select2 '],
            'choice_attr' => static fn (Event $e) => ['data-center' => $e->getCenter()->getId()],
            'choiceloader' => function (Options $options) {
                $centers = $this->filterCenters($options);

                return new EventChoiceLoader($this->eventRepository, $centers);
            },
        ]);
    }

    public function getParent(): ?string
    {
        return EntityType::class;
    }

    /**
     * @return array
     */
    protected function filterCenters(Options $options)
    {
        $user = $this->security->getUser();

        if (!$user instanceof User) {
            return [];
        }

        // option role
        if (null === $options['role']) {
            $centers = array_map(
                static fn (GroupCenter $g) => $g->getCenter(),
                $user->getGroupCenters()->toArray()
            );
        } else {
            $centers = $this->authorizationHelper->getReachableCenters(
                $user,
                $options['role']
            );
        }

        // option center
        if (null === $options['centers']) {
            // we select all selected centers
            $selectedCenters = $centers;
        } else {
            $selectedCenters = [];
            $optionsCenters = \is_array($options['centers']) ?
                $options['centers'] : [$options['centers']];

            foreach ($optionsCenters as $c) {
                // check that every member of the array is a center
                if (!$c instanceof Center) {
                    throw new \RuntimeException('Every member of the "centers" option must be an instance of '.Center::class);
                }

                if (
                    !\in_array($c->getId(), array_map(
                        static fn (Center $c) => $c->getId(),
                        $centers
                    ), true)
                ) {
                    throw new AccessDeniedException('The given center is not reachable');
                }
                $selectedCenters[] = $c;
            }
        }

        return $selectedCenters;
    }
}
