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

use Chill\MainBundle\Form\Type\DataTransformer\EntityToJsonTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerInterface;

/**
 * Pick user dymically, using vuejs module "AddPerson".
 */
class PickThirdpartyDynamicType extends AbstractType
{
    public function __construct(private readonly DenormalizerInterface $denormalizer, private readonly SerializerInterface $serializer, private readonly NormalizerInterface $normalizer) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addViewTransformer(new EntityToJsonTransformer($this->denormalizer, $this->serializer, $options['multiple'], 'thirdparty'));
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['multiple'] = $options['multiple'];
        $view->vars['types'] = ['thirdparty'];
        $view->vars['uniqid'] = uniqid('pick_user_dyn');
        $view->vars['suggested'] = [];
        $view->vars['as_id'] = true === $options['as_id'] ? '1' : '0';
        $view->vars['submit_on_adding_new_entity'] = true === $options['submit_on_adding_new_entity'] ? '1' : '0';

        foreach ($options['suggested'] as $tp) {
            $view->vars['suggested'][] = $this->normalizer->normalize($tp, 'json', ['groups' => 'read']);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefault('multiple', false)
            ->setAllowedTypes('multiple', ['bool'])
            ->setDefault('compound', false)
            ->setDefault('suggested', [])
            ->setDefault('as_id', false)
            ->setAllowedTypes('as_id', ['bool'])
            ->setDefault('submit_on_adding_new_entity', false)
            ->setAllowedTypes('submit_on_adding_new_entity', ['bool']);
    }

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