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

namespace VisualM\FormBundle\ContentScan;

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

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

    /**
     * {@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];
            }

            $formManager = $this->container->get('visualm.form.manager.form');
            $formRenderer = $this->container->get('visualm.form.renderer.form');

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

            return $formRenderer->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];
            }

            $formManager = $this->container->get('visualm.form.manager.form');
            $formRenderer = $this->container->get('visualm.form.renderer.form');

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

            return $formRenderer->renderForm($form, $matches[2]);

        }, $content);


        return $content;
    }

}
