<?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\Language;
use Chill\MainBundle\Form\Type\DataTransformer\MultipleObjectsToIdTransformer;
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 for languages (multiple).
 */
class Select2LanguageType 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 MultipleObjectsToIdTransformer($this->em, Language::class);
        $builder->addModelTransformer($transformer);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $languages = $this->em->getRepository(Language::class)->findAll();
        $preferredLanguages = $this->parameterBag->get('chill_main.available_languages');
        $choices = [];
        $preferredChoices = [];

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

        foreach ($preferredLanguages as $l) {
            $preferredChoices[$l] = $choices[$l];
        }

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

        $resolver->setDefaults([
            'class' => Language::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_language';
    }

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