<?php

namespace Comitium5\DesignerBundle\Form\Type\WidgetParameters;

use Comitium5\DesignerBundle\Form\Resolver\WidgetParametersResolver;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class WidgetParametersValueType
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Form\Type\WidgetParameters
 */
class WidgetParametersValueType extends AbstractType
{
    /**
     * @var WidgetParametersResolver
     */
    private $resolver;

    /**
     * @param WidgetParametersResolver $resolver
     */
    public function __construct(WidgetParametersResolver $resolver)
    {
        $this->resolver = $resolver;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {

            $entity = $event->getData();
            $form   = $event->getForm();

            $data = $this
                ->resolver
                ->resolve($entity);

            if ($data) {
                try {
                    $form->add('value', $data['type'], $data['options']);
                } catch (\Throwable $e) {
                }
            }
        });

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {

            $entity = $event->getData();
            $type = $entity->getType();

            if ($type === WidgetParametersResolver::TYPE_CROPS ||
                $type === WidgetParametersResolver::TYPE_CROPS_GROUPS
            ) {
                $this
                    ->resolver
                    ->transformCropsValue($entity);
            } else {
                $this
                    ->resolver
                    ->transformFromValue($entity);
            }
        });
    }

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