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

use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Config\ConfigPersonAltNamesHelper;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PersonAltNameType extends AbstractType
{
    public function __construct(private readonly ConfigPersonAltNamesHelper $configHelper, private readonly TranslatableStringHelper $translatableStringHelper) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        foreach ($this->getKeyChoices() as $label => $key) {
            $builder->add(
                $key,
                $options['force_hidden'] ? HiddenType::class : TextType::class,
                [
                    'label' => $label,
                    'required' => false,
                    'empty_data' => '',
                ]
            );
        }

        $builder->setDataMapper(new \Chill\PersonBundle\Form\DataMapper\PersonAltNameDataMapper());
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefault('class', \Chill\PersonBundle\Entity\PersonAltName::class)
            ->setDefined('force_hidden')
            ->setAllowedTypes('force_hidden', 'bool')
            ->setDefault('force_hidden', false);
    }

    protected function getKeyChoices()
    {
        $choices = $this->configHelper->getChoices();
        $translatedChoices = [];

        foreach ($choices as $key => $labels) {
            $label = $this->translatableStringHelper->localize($labels);
            $translatedChoices[$label] = $key;
        }

        return $translatedChoices;
    }
}
