<?php
/**
 * Twig Loader that gets the Twig source from the Form Entities.
 * This is used in the FormHelper to render the Form
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Twig;

use Twig_Error_Loader;
use Twig_LoaderInterface;
use VisualM\FormBundle\Entity\FormRepository;

/**
 * Twig Loader that gets the Twig source from the Form Entities.
 * This is used in the FormHelper to render the Form
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class FormHtmlLoader implements Twig_LoaderInterface
{
    /**
     * Form Manager
     * @var FormRepository
     */
    private $formManager;

    /**
     * Constructor
     * 
     * @param FormRepository $formManager Form Manager
     */
    public function __construct(FormRepository $formManager)
    {
        $this->formManager = $formManager;
    }

    /**
     * {@inheritdoc}
     */
    public function getSource($name)
    {
        if (preg_match('/^VisualMFormEntity~([1-9]+[0-9]*)~(formHtml|emailHtml|kopieEmailHtml)/', $name, $matches) != 0) {
            if (null === ($form = $this->formManager->getFirst([ 'id' => $matches[1] ]))) {
                throw new Twig_Error_Loader(sprintf('VisualM Form Entity with id %d not found', $matches[1]));
            }
            if ($matches[2] == 'formHtml') {
                return $form->getFormHtml();
            } elseif ($matches[2] == 'emailHtml') {
                return $form->getEmailHtml();
            } elseif ($matches[2] == 'kopieEmailHtml') {
                return $form->getKopieEmailHtml();
            } else {
                return '';
            }
        }

        throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
        
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheKey($name)
    {
        // Twig in production won't check the freshness of a twig template as it caching is aggresive
        // Therefor change the caching key if the content is changed
        if (preg_match('/^VisualMFormEntity~([1-9]+[0-9]*)~(formHtml|emailHtml|kopieEmailHtml)/', $name, $matches) != 0) {
            if (null === ($form = $this->formManager->getFirst([ 'id' => $matches[1] ]))) {
                return $name;
            }
            if ($matches[2] == 'formHtml') {
                return $name . ':' . sha1($form->getFormHtml());
            } elseif ($matches[2] == 'emailHtml') {
                return $name . ':' . sha1($form->getEmailHtml());
            } elseif ($matches[2] == 'kopieEmailHtml') {
                return $name . ':' . sha1($form->getKopieEmailHtml());
            } else {
                return '';
            }
        }

        return $name;
    }

    /**
     * {@inheritdoc}
     */
    public function isFresh($name, $time)
    {
        return true;
    }

   
    
}