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

use Chill\MainBundle\Entity\Center;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;

/**
 * Lazy load third parties.
 *
 * @deprecated As the PickThirdPartyType is deprecated, this should not be in use
 */
class ThirdPartyChoiceLoader implements ChoiceLoaderInterface
{
    /**
     * @var Center
     */
    protected $center;

    /**
     * @var \Chill\ThirdPartyBundle\Entity\ThirdParty[]
     */
    protected $lazyLoadedParties = [];

    /**
     * @var EntityRepository
     */
    protected $partyRepository;

    public function __construct(Center $center, EntityRepository $partyRepository)
    {
        $this->center = $center;
        $this->partyRepository = $partyRepository;
    }

    public function loadChoiceList($value = null): ChoiceListInterface
    {
        return new ArrayChoiceList($this->lazyLoadedParties, $value);
    }

    public function loadChoicesForValues($values, $value = null)
    {
        $choices = [];

        foreach ($values as $value) {
            $party = $this->partyRepository->find($value);

            if (false === \in_array($this->center, $party->getCenters()->toArray(), true)) {
                throw new \RuntimeException("the party's center is not authorized");
            }

            $choices[] = $party;
        }

        return $choices;
    }

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

        return $values;
    }
}
