<?php
/**
 * Scan for references to Forms
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\ContentScan;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use VisualM\CmsBundle\ContentScan\ContentHandlerInterface;

/**
 * Scan for references to Forms
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class Form extends ContainerAware implements ContentHandlerInterface, ContainerAwareInterface
{

    /**
     * {@inheritDoc}
     */
    public function getPriority()
    {
        return ContentHandlerInterface::PRIORITY_LOW;
    }

    /**
     * {@inheritDoc}
     */
    public function handle($content)
    {
        $ignore = [];
        
        $content = preg_replace_callback('/\[form\|([a-z_\-0-9]+)\]/', function($matches) use (&$ignore) {

            if (in_array($matches[1], $ignore)) {
                return $matches[0];
            }

            $form_manager = $this->container->get('visualm.form.manager.form');
            $form_helper = $this->container->get('visualm.form.helper.form');

            if (null === ($form = $form_manager->getFirst([ 'referentie' => $matches[1] ]))) {
                $ignore[] = $matches[1];
                return $matches[0];
            }

            $form_helper = $this->container->get('visualm.form.helper.form');
            return $form_helper->renderForm($form);

        }, $content);

        $content = preg_replace_callback('/\[form\-with\-url\|([a-z_\-0-9]+)\|([^\]]+)\]/', function($matches) use (&$ignore) {

            if (in_array($matches[1], $ignore)) {
                return $matches[0];
            }

            $form_manager = $this->container->get('visualm.form.manager.form');
            $form_helper = $this->container->get('visualm.form.helper.form');

            if (null === ($form = $form_manager->getFirst([ 'referentie' => $matches[1] ]))) {
                $ignore[] = $matches[1];
                return $matches[0];
            }

            $form_helper = $this->container->get('visualm.form.helper.form');
            return $form_helper->renderForm($form, $matches[2]);

        }, $content);


        return $content;
    }

}
