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

use Chill\EventBundle\Entity\Event;
use Chill\EventBundle\Repository\EventRepository;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;

/**
 * Class EventChoiceLoader.
 */
class EventChoiceLoader implements ChoiceLoaderInterface
{
    /**
     * @var array
     */
    protected $centers = [];

    protected $eventRepository;

    /**
     * @var array
     */
    protected $lazyLoadedEvents = [];

    /**
     * EventChoiceLoader constructor.
     */
    public function __construct(
        EventRepository $eventRepository,
        ?array $centers = null,
    ) {
        $this->eventRepository = $eventRepository;

        if (null !== $centers) {
            $this->centers = $centers;
        }
    }

    /**
     * @param null $value
     */
    public function loadChoiceList($value = null): ChoiceListInterface
    {
        return new \Symfony\Component\Form\ChoiceList\ArrayChoiceList(
            $this->lazyLoadedEvents,
            static fn (Event $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;
            }

            $event = $this->eventRepository->find($value);

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

            $choices[] = $event;
        }

        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->lazyLoadedEvents[$id] = $choice;
        }

        return $values;
    }

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