<?php
/**
 * Update MetaTags when MetaTagPreset is changed
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\TagManagerBundle\Doctrine\EventListener;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use VisualM\TagManagerBundle\Entity\MetaTag;
use VisualM\TagManagerBundle\Entity\MetaTagPreset;



/**
 * Update MetaTags when MetaTagPreset is changed
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class UpdateTagFromPresetSubscriber extends ContainerAware implements EventSubscriber, ContainerAwareInterface
{
    /**
     * Needs Flush
     * @var bool
     */
    private $needsFlush = false;
    
    /**
     * Specifies the list of events to listen
     *
     * @return array
     */
    public function getSubscribedEvents()
    {
        return array(
            'postUpdate',
            'postFlush'
        );
    }

    /**
     * postUpdate event
     *
     * @param LifecycleEventArgs $args Event Data
     */
    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if (!($entity instanceof MetaTagPreset)) {
            return;
        }
        foreach($entity->getMetaTags() as $meta_tag) {
            /* @var $meta_tag MetaTag */
            $persist = false;
            if (
                !$meta_tag->getInhoudGewijzigd() AND
                (($meta_tag->getInhoud() != $entity->getInhoud()) OR ($meta_tag->getInhoudIsExpression() != $entity->getInhoudIsExpression()))
            ) {
                $meta_tag->setInhoud($entity->getInhoud());
                $meta_tag->setInhoudIsExpression($entity->getInhoudIsExpression());
                $persist = true;
            }
            if (
                !$meta_tag->getZichtbaarGewijzigd() AND
                (($meta_tag->getZichtbaar() != $entity->getZichtbaar()) OR ($meta_tag->getZichtbaarIsExpression() != $entity->getZichtbaarIsExpression()))
            ) {
                $meta_tag->setZichtbaar($entity->getZichtbaar());
                $meta_tag->setZichtbaarIsExpression($entity->getZichtbaarIsExpression());
                $persist = true;
            }
            if ($persist) {
                $args->getEntityManager()->persist($entity);
                $this->needsFlush = true;
            }
        }
    }

    /**
     * postFlush event
     *
     * @param PostFlushEventArgs $eventArgs Event Data
     */
    public function postFlush(PostFlushEventArgs $eventArgs)
    {
        if ($this->needsFlush) {
            $this->needsFlush = false;
            $eventArgs->getEntityManager()->flush();
        }
    }

    
}
