<?php
/**
 * CK Editor Widget Provider for Form
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\CkWidget;

use VisualM\FormBundle\CkWidget\Configuration\FormConfiguration;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Translation\TranslatorInterface;
use VisualM\CkWidgetsBundle\Model\CkWidgetProviderInterface;
use VisualM\CkWidgetsBundle\Model\CkWidgetProviderResponse;
use VisualM\FormBundle\Entity\FormRepository;

/**
 * CK Editor Widget Provider for Form
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class FormProvider implements CkWidgetProviderInterface
{

    /**
     * Form Manager
     * @var FormRepository
     */
    private $formManager;

    /**
     * Templating Engine
     * @var EngineInterface
     */
    private $templating;

    /**
     * Translator
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * Form Factory
     * @var FormFactoryInterface
     */
    private $formFactory;

    /**
     * Authorization Checker
     * @var AuthorizationCheckerInterface
     */

    private $authChecker;

    /**
     * Constructor
     * 
     * @param FormRepository                $formManager     Form Manager
     * @param EngineInterface               $templating      Templating Engine
     * @param TranslatorInterface           $translator      Translator
     * @param FormFactoryInterface          $formFactory     Form Factory
     * @param AuthorizationCheckerInterface $authChecker     Authorization Checker
     */
    function __construct(
        FormRepository $formManager,
        EngineInterface $templating,
        TranslatorInterface $translator,
        FormFactoryInterface $formFactory,
        AuthorizationCheckerInterface $authChecker
    ) {
        $this->formManager = $formManager;
        $this->templating = $templating;
        $this->translator = $translator;
        $this->formFactory = $formFactory;
        $this->authChecker = $authChecker    ;
    }

    /**
     * {@inheritdoc}
     */
    public function getTitle()
    {
        return $this->translator->trans('ckeditor_widget.form.title', [], 'backend');
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return $this->translator->trans('ckeditor_widget.form.description', [], 'backend');
    }

    /**
     * {@inheritdoc}
     */
    public function isVisible()
    {
        return (true === $this->authChecker->isGranted('ROLE_PERM_LIST_FORM'));
    }

    /**
     * {@inheritdoc}
     */
    public function handle(Request $request, $currentData)
    {

        // Create configuration object
        $configuration = new FormConfiguration($currentData);

        $choices = $this->getFormChoices();

        // Create form
        $form = $this->formFactory->createBuilder(FormType::class, $configuration)
            ->add('formReferentie', ChoiceType::class, [
                'label' => $this->translator->trans('ckeditor_widget.form.form_referentie.label', [], 'forms'),
                'placeholder' => $this->translator->trans('ckeditor_widget.form.form_referentie.placeholder', [], 'forms'),
                'choices' => $choices
            ])
            ->getForm();

        // Handle form submit
        $form->handleRequest($request);
        if ($form->isSubmitted() and $form->isValid()) {

            $caption = $this->translator->trans('ckeditor_widget.form.caption', [
                '%formulier%' => $choices[$configuration->getFormReferentie()]
            ], 'backend');

            return CkWidgetProviderResponse::dataResponse($configuration->getData(), $caption);
        }

        // Render view to return
        $html = $this->templating->render('VisualMFormBundle:CkWidget:form.html.twig', [
            'form' => $form->createView()
        ]);

        return CkWidgetProviderResponse::htmlResponse($html, $this->translator->trans('ckeditor_widget.form.title', [], 'backend'));

    }

    /**
     * {@inheritdoc}
     */
    public function getScriptHtml()
    {
        return '';
    }

    /**
     * Get Form Choices
     * 
     * @return array<string>
     */
    private function getFormChoices()
    {
        $choices = [];
        foreach($this->formManager->getIndex([], [ 'titel', 'ASC' ]) as $form) {
            $choices[$form->getReferentie()] = $form->getTitel();
        }
        return $choices;
    }

}
