<?php

namespace Comitium5\DesignerBundle\Form\Type\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FormType;

/**
 * Class ViewTypeExtension
 * @package ComitiumSuite\Bundle\CoreBundle\Form\Extension
 */
class ViewTypeExtension extends AbstractTypeExtension
{
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefined([
                'view_type',
                'help',
                'ico',
                'placeholder',
                'translatable',
            ])
            ->setDefaults([
                'view_type' => null
            ]);
    }

    /**
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $resolver = new OptionsResolver();

        $parameters = ['ico', 'placeholder', 'help', 'label'];

        $resolver
            ->setDefined($parameters);

        $opt = array();

        foreach ($options as $label => $option) {
            if (in_array($label, $parameters) && !is_null($option)) {
                $opt[$label] = $option;
            }
        }

        $resolved = $resolver->resolve($opt);

        foreach ($parameters as $parameter) {
            if (!isset($resolved[$parameter])) {
                $resolved[$parameter] = null;
            }
        }

        if ($resolved) {
            $view->vars = array_merge($view->vars, $resolved);
        }

        if (isset($options['view_type']) && !empty($options['view_type'])) {
            $view->vars['view_type'] = $options['view_type'];
        }

        if (isset($resolved['help']) && !empty($resolved['help'])) {
            $view->vars['help'] = $resolved['help'];
        }

        $view->vars['view_type'] = $options['view_type'];

        $view->vars['translatable'] = isset($options['translatable']) ? $options['translatable'] : true;
    }

    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType()
    {
        return FormType::class;
    }
}
