<?php

namespace App\Form\Type;

use App\Entity\GlobalParameter;
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 GlobalParameterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', HiddenType::class, ['data' => $options['name_param']])
            ->add('mandatory', HiddenType::class, ['data' => $options['_mandatory']])
            ->add('description', HiddenType::class, ['data' => $options['_description']])
        ;
        if (!isset($options['_type'])) {
            $builder
                ->add('value', TextType::class, [
                    'label' => false,
                    'constraints' => $options['constraints_param'],
                    'data' => $options['_data'],
                    'attr' => [
                        'placeholder' => $options['_placeholder'],
                    ],
                ])
            ;
        } else {
            $params = [
                'label' => false,
                'constraints' => $options['constraints_param'],
                'data' => $options['_data'],
                'attr' => [
                    'placeholder' => $options['_placeholder'],
                ],
            ];
            $params = array_merge($params, (isset($options['_type_options']) ? $options['_type_options'] : []));
            $builder
                ->add('value', $options['_type'], $params)
            ;
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => GlobalParameter::class,
            'name_param' => '',
            '_placeholder' => '',
            '_mandatory' => true,
            '_data' => null,
            '_description' => '',
            '_type' => null,
            '_type_options' => null,
            'constraints_param' => [],
            'error_bubbling' => false,
            // 'cascade_validation' => true
        ]);
    }

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