<?php

namespace Comitium5\DesignerBundle\Form\Type\CKEditor;

use Comitium5\DesignerBundle\Form\Extension\CKEditorExtension;
use Comitium5\DesignerBundle\Form\Resolver\CkEditorResolver;
use Comitium5\DesignerBundle\Provider\Locale\LocaleProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class CKEditorType
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Form\Type\CKEditor
 */
class CKEditorType extends AbstractType
{
    /**
     * @var LocaleProvider
     */
    private $localeProvider;

    /**
     * @var array
     */
    private $config;

    /**
     * @var CkEditorResolver
     */
    private $resolver;

    /**
     * CKEditorType constructor.
     *
     * @param array $config
     * @param LocaleProvider $localeProvider
     * @param CkEditorResolver $ckEditorResolver
     */
    public function __construct(
        array $config,
        LocaleProvider $localeProvider,
        CkEditorResolver $ckEditorResolver
    )
    {
        $this->config = $config;
        $this->localeProvider = $localeProvider;
        $this->resolver = $ckEditorResolver;
    }

    /**
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     * @throws \Exception
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['ckeditor']['plugins'] = $this->config['plugins'];

        if (isset($options["locale"])) {
            $locale = $options["locale"];
        } elseif (isset($view->vars['attr']['lang'])) {
            $locale = $view->vars['attr']['lang'];
        } else {
            $locale = $this->localeProvider->getDefaultLocale()->getCode();
        }

        $view->vars['attr']['lang'] = $locale;

        foreach (CKEditorExtension::getExtensionParameters() as $parameter) {
            if(!array_key_exists($options["$parameter"], $this->config["{$parameter}s"])) {
                throw new \Exception(sprintf("$parameter %s is not defined", $options[$parameter]));
            }
        }
        $config = $this->resolver->resolve($options);

        $view->vars['ckeditor']['config'] = $config["config"];
    }

    /**
     * @return string
     */
    public function getParent()
    {
        return TextAreaType::class;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefined([
            "locale"
        ]);
    }

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