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

use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Form\Type\DataTransformer\ObjectToIdTransformer;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Extends choice to allow adding select2 library on widget.
 */
class Select2CountryType extends AbstractType
{
    public function __construct(private readonly RequestStack $requestStack, private readonly ObjectManager $em, protected TranslatableStringHelper $translatableStringHelper, protected ParameterBagInterface $parameterBag) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $transformer = new ObjectToIdTransformer($this->em, Country::class);
        $builder->addModelTransformer($transformer);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $countries = $this->em->getRepository(Country::class)->findAll();
        $choices = [];
        $preferredCountries = $this->parameterBag->get('chill_main.available_countries');
        $preferredChoices = [];

        foreach ($countries as $c) {
            $choices[$c->getId()] = $this->translatableStringHelper->localize($c->getName());
        }

        foreach ($preferredCountries as $pc) {
            foreach ($countries as $c) {
                if ($c->getCountryCode() === $pc) {
                    $preferredChoices[$c->getId()] = $this->translatableStringHelper->localize($c->getName());
                }
            }
        }

        asort($choices, \SORT_STRING | \SORT_FLAG_CASE);

        $resolver->setDefaults([
            'class' => Country::class,
            'choices' => array_combine(array_values($choices), array_keys($choices)),
            'preferred_choices' => array_combine(array_values($preferredChoices), array_keys($preferredChoices)),
        ]);
    }

    public function getBlockPrefix()
    {
        return 'select2_chill_country';
    }

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