<?php
/**
 * Form Renderer
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Renderer;

use Symfony\Component\Form\FormFactory;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Templating\EngineInterface;
use VisualM\FormBundle\Entity\Form as FormEntity;
use VisualM\FormBundle\Form\Data\GeneratedFormData;
use VisualM\FormBundle\Form\Type\GeneratedFormType;

/**
 * Form Renderer
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class FormRenderer
{
    
    /**
     * Request Stack
     * @var RequestStack
     */
    private $requestStack;

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

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

    /**
     * Renderered Forms
     * @var array
     */
    private $renderedForms = [];
    
    /**
     * Constructor
     * 
     * @param RequestStack    $requestStack Request Stack
     * @param FormFactory     $formFactory  Form Factory
     * @Param EngineInterface $templating   Templating Engine
     */
    public function __construct(RequestStack $requestStack, FormFactory $formFactory, EngineInterface $templating)
    {
        $this->requestStack = $requestStack;
        $this->formFactory = $formFactory;
        $this->templating = $templating;
    }

    /**
     * Render Form
     *
     * @param FormEntity  $formEntity        FormEntity
     * @param string|null $customRedirectUrl Custom Redirect Url
     *
     * @return string HTML Form HTML
     */
    public function renderForm(FormEntity $formEntity, $customRedirectUrl = null)
    {
        // Create form
        $form = $this->formFactory->createNamed(
            'vm_form_' . $formEntity->getReferentie(),
            GeneratedFormType::class,
            new GeneratedFormData(),
            [
                'mapped' => false,
                'fields' => $formEntity->getFields()
            ]
        );

        // Create form, update it from request and mark it as rendered
        $form->handleRequest($this->requestStack->getMasterRequest());
        $this->renderedForms[] = [ $form, $formEntity, $customRedirectUrl ];

        $html = $this->templating->render(sprintf('VisualMFormEntity~%d~formHtml', $formEntity->getId()), [
            'form' => $form->createView(),
            'form_entity' => $formEntity
        ]);

        return $html;
        
    }

    /**
     * Get Rendered Forms
     *
     * @return array Rendered Forms
     */
    public function getRenderedForms()
    {
        return $this->renderedForms;
    }

}