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

use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Repository\PersonRepository;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;

/**
 * Allow to load a list of person.
 */
class PersonChoiceLoader implements ChoiceLoaderInterface
{
    protected array $centers = [];

    protected array $lazyLoadedPersons = [];

    public function __construct(
        protected PersonRepository $personRepository,
        ?array $centers = null,
    ) {
        if (null !== $centers) {
            $this->centers = $centers;
        }
    }

    /**
     * @param null $value
     */
    public function loadChoiceList($value = null): ChoiceListInterface
    {
        return new \Symfony\Component\Form\ChoiceList\ArrayChoiceList(
            $this->lazyLoadedPersons,
            static fn (Person $p) => \call_user_func($value, $p)
        );
    }

    /**
     * @param null $value
     *
     * @return array
     */
    public function loadChoicesForValues(array $values, $value = null)
    {
        $choices = [];

        foreach ($values as $value) {
            if (empty($value)) {
                continue;
            }

            $person = $this->personRepository->find($value);

            if (
                $this->hasCenterFilter()
                && !\in_array($person->getCenter(), $this->centers, true)
            ) {
                throw new \RuntimeException('chosen a person not in correct center');
            }

            $choices[] = $person;
        }

        return $choices;
    }

    /**
     * @param null $value
     *
     * @return array|string[]
     */
    public function loadValuesForChoices(array $choices, $value = null)
    {
        $values = [];

        foreach ($choices as $choice) {
            if (null === $choice) {
                $values[] = null;

                continue;
            }

            $id = \call_user_func($value, $choice);
            $values[] = $id;
            $this->lazyLoadedPersons[$id] = $choice;
        }

        return $values;
    }

    /**
     * @return bool
     */
    protected function hasCenterFilter()
    {
        return \count($this->centers) > 0;
    }
}
