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

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Form\ChoiceLoader\PersonChoiceLoader;
use Chill\PersonBundle\Repository\PersonRepository;
use Chill\PersonBundle\Search\PersonSearch;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
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\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * This type allow to pick a person.
 *
 * The form is embedded in a select2 input.
 *
 * The people may be filtered :
 *
 * - with the `centers` option, only the people associated with the given center(s)
 * are seen. May be an instance of `Chill\MainBundle\Entity\Center`, or an array of
 * `Chill\MainBundle\Entity\Center`. By default, all the reachable centers as selected.
 * - with the `role` option, only the people belonging to the reachable center for the
 * given role are displayed.
 */
final class PickPersonType extends AbstractType
{
    public function __construct(
        private readonly PersonRepository $personRepository,
        private readonly TokenStorageInterface $tokenStorage,
        private readonly AuthorizationHelper $authorizationHelper,
        private readonly UrlGeneratorInterface $urlGenerator,
        private readonly TranslatorInterface $translator,
    ) {}

    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' => PersonSearch::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)
            ->setDefined('role')
            ->addAllowedTypes('role', ['string', 'null'])
            ->setDefault('role', null);

        // add the default options
        $resolver->setDefaults([
            'class' => Person::class,
            'choice_label' => static fn (Person $p) => $p->getFirstname().' '.$p->getLastname(),
            'placeholder' => 'Pick a person',
            'choice_attr' => static fn (Person $p) => [
                'data-center' => $p->getCenter()->getId(),
            ],
            'attr' => ['class' => 'select2 '],
            'choice_loader' => function (Options $options) {
                $centers = $this->filterCentersfom($options);

                return new PersonChoiceLoader($this->personRepository, $centers);
            },
        ]);
    }

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

    protected function filterCentersfom(Options $options)
    {
        $user = $this->tokenStorage->getToken()->getUser();
        if (!$user instanceof User) {
            throw new \UnexpectedValueException('user should be an instance of '.User::class);
        }

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

        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;
    }
}
