<?php

namespace Comitium5\DesignerBundle\Form\Type\WidgetParameters;

use Comitium5\DesignerBundle\Form\DataTransformer\ArrayToStringTransformer;
use Comitium5\DesignerBundle\Form\Model\WidgetParameters\WidgetParametersValue;
use Comitium5\DesignerBundle\Form\Resolver\WidgetParametersResolver;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class WidgetParametersType
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Form\Type\WidgetParameters
 */
class WidgetParametersType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('parameters', CollectionType::class, [
                'entry_type' => WidgetParametersValueType::class,
                'label' => false,
                'allow_add' => false,
                'entry_options' => [
                    'label' => false,
                    'data_class' => WidgetParametersValue::class,
                ],
            ])
            ->add('uuid', HiddenType::class)
            ->add(
                $builder
                    ->create('locales', HiddenType::class, ['required' => false])
                    ->addViewTransformer(new ArrayToStringTransformer())
            )
        ;
    }

    /**
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        parent::finishView($view, $form, $options);

        foreach ($form->getData()->getParameters() as $parameter) {
            $type = $parameter->getType();

            if ($type !== WidgetParametersResolver::TYPE_FORMAT) {
                continue;
            }

            $view->vars['_hasFormat'] = true;
        }
    }

    /**
     * @param FormView      $view
     * @param FormInterface $form
     * @param array         $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['_hasFormat'] = $options['_hasFormat'];
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            "_hasFormat" => false,
        ]);
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'widget_parameters';
    }
}
