<?php

namespace App\Form;

use App\Entity\Setting;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\AbstractType;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

class SettingType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        // https://hugoderre.com/fr/blog/integrer-un-editeur-wysiwyg-dans-symfony
        
        $builder
            ->add('setting', HiddenType::class)
            ->add('type', HiddenType::class)
            // ->add('value', CKEditorType::class, [ 'required' => true, 'attr' => ['rows' => 30], 'config' => ['toolbar' => 'basic'] ])
        ;

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use($options) {
            $setting = $event->getData(); //recuperation de l'objet sur lequel le formulaire se base
            $form = $event->getForm(); //recuperation du formulaire
            //en fonction du type de l'utilisateur les champs sont différents

            switch ($setting->getType()) {
                case 'html':
                    $form->add('value', 
                                CKEditorType::class, 
                                [ 
                                    'required' => true, 
                                    'attr' => ['rows' => 30], 
                                    'config' => ['toolbar' => 'basic'],
                                    'translation_domain' => 'admin' 
                                ]);
                    break;
                case 'txt':
                    $form->add('value', 
                               TextType::class, 
                               [ 
                                'required' => false, 
                                'attr' => ['maxlength' => 255],
                                'translation_domain' => 'admin' 
                               ]);
                    break;
                
                default:
                    throw new \Exception("");
            }
        });
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Setting::class,
        ]);
    }
}
