<?php
/**
 * ManageMetaTagSetController
 *
 * @author Visual Media
 */
namespace VisualM\TagManagerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\OptionsResolver\Exception\InvalidArgumentException;

use VisualM\BlockManagerBundle\Annotation\Block;
use VisualM\BlockManagerBundle\Annotation\BlockLayout;
use VisualM\TagManagerBundle\Entity\MetaTagPresetRepository;
use VisualM\TagManagerBundle\Entity\MetaTagSet;
use VisualM\TagManagerBundle\Form\Type\MetaTagSetType;
use VisualM\TagManagerBundle\Model\MetaTagSetManager;

/**
 * ManageMetaTagSetController
 *
 * @BlockLayout(layout="backend")
 * @Block(view="page_header", position="titlebar", priority=1)
 * @Block(view="flashmessages", position="flashmessages")
 *
 * @author Visual Media
 */
class ManageMetaTagSetController extends Controller
{
    /**
     * Handle saving of Gebruiker
     *
     * @param MetaTagSet $metaTagSet     MetaTagSet
     * @param Form       $metaTagSetForm MetaTagSet Form
     *
     * @return Response
     */
    protected function handleSave(MetaTagSet $metaTagSet, Form $metaTagSetForm)
    {
        $translator = $this->container->get('translator');

        $meta_tag_set_manager = $this->container->get('visualm.tag_manager.manager.meta_tag_set');
        /* @var $meta_tag_set_manager MetaTagSetManager */

        $meta_tag_preset_manager = $this->container->get('visualm.tag_manager.manager.meta_tag_preset');
        /* @var $meta_tag_preset_manager MetaTagPresetRepository */

        // Persist tag presets
        foreach($metaTagSet->getMetaTagPresets() as $meta_tag_preset) {
            $meta_tag_preset->setMetaTagSet($metaTagSet);
            $meta_tag_preset_manager->saveItem($meta_tag_preset, [ "flush" => false ]);
        }

        $meta_tag_set_manager->saveItem($metaTagSet);

        $this->addFlash(
            'success',
            $translator->trans('meta_tag_set.saved', array(), 'flashmessage')
        );

        $this->container->get('session')->set('meta_tag_set.lastEdit', $metaTagSet->getId());

        if ($metaTagSetForm->get('save')->isClicked()) {
            return $this->redirect($this->generateUrl('manage_meta_tag_set_edit', array('id' => $metaTagSet->getId())));
        } else {
            return $this->redirect($this->generateUrl('manage_meta_tag_set_index'));
        }
    }

    /**
     * Show list of MetaTagSets
     *
     * @Block(view="VisualMTagManagerBundle:ManageMetaTagSet:index.html.twig", position="main")
     * @Block(view="VisualMTagManagerBundle:ManageMetaTagSet:indexActions.html.twig", position="titlebar-actions")
     *
     */
    public function indexAction()
    {
        $translator = $this->container->get('translator');
        $authChecker = $this->container->get('security.authorization_checker');

        if (!$authChecker->isGranted('ROLE_PERM_LIST_META_TAG_SET')) {
             throw new AccessDeniedHttpException($translator->trans('meta_tag_set.access_denied', array(), 'exception'));
        }

        $admin_list = $this->container->get('visualm.tag_manager.admin_list.meta_tag_set');

        $factories = $this->container->get('visualm.tag_manager.manager.meta_tag_set')->getFactories();

        return array(
            'page_title' => $translator->trans('meta_tag_set.index.page_title', array(), 'backend'),
            'admin_list' => $admin_list,
            'factories' => isset($factories) ? $factories : null,
        );
    }

    /**
     * Add MetaTagSet
     *
     * @Block(view="VisualMTagManagerBundle:ManageMetaTagSet:form.html.twig", position="main")
     * @Block(view="VisualMTagManagerBundle:ManageMetaTagSet:toIndex.html.twig", position="titlebar")
     *
     * @param Request $request Request
     *
     * @return View
     */
    public function addAction(Request $request, $factoryService)
    {
        $translator = $this->container->get('translator');
        $authChecker = $this->container->get('security.authorization_checker');

        $meta_tag_set_manager = $this->container->get('visualm.tag_manager.manager.meta_tag_set');

        if (null === ($factory = $meta_tag_set_manager->getFactory($factoryService))) {
            throw new InvalidArgumentException($translator->trans('meta_tag_set.invalid_factory', array(), 'exception'));
        }

        if (!$authChecker->isGranted('ROLE_PERM_ADD_META_TAG_SET')) {
            throw new AccessDeniedHttpException($translator->trans('meta_tag_set.access_denied', array(), 'exception'));
        }

        $meta_tag_set = new MetaTagSet();
        $meta_tag_set->setFactoryService($factoryService);

        $meta_tag_set_form = $this->createForm(MetaTagSetType::class, $meta_tag_set);

        $meta_tag_set_form->handleRequest($request);
        if ($meta_tag_set_form->isValid()) {
            return $this->handleSave($meta_tag_set, $meta_tag_set_form);
        }

        return array(
            'page_title' => $translator->trans('meta_tag_set.add.page_title', array(), 'backend'),
            'meta_tag_set' => $meta_tag_set,
            'meta_tag_set_form' => $meta_tag_set_form->createView(),
            'data_fields' => $this->container->get('visualm.tag_manager.util.extended_data_dictionary')->getAvailableFields()
        );
    }

    /**
     * Edit MetaTagSet
     *
     * @Block(view="VisualMTagManagerBundle:ManageMetaTagSet:form.html.twig", position="main")
     * @Block(view="VisualMTagManagerBundle:ManageMetaTagSet:toIndex.html.twig", position="titlebar")
     *
     * @param Request $request Request
     * @param int     $id      MetaTagSet Id
     *
     * @return array View Data
     */
    public function editAction(Request $request, $id)
    {
        $translator = $this->container->get('translator');
        $authChecker = $this->container->get('security.authorization_checker');

        if (!$authChecker->isGranted('ROLE_PERM_EDIT_META_TAG_SET')) {
            throw new AccessDeniedHttpException($translator->trans('meta_tag_set.access_denied', array(), 'exception'));
        }

        $meta_tag_set_manager = $this->container->get('visualm.tag_manager.manager.meta_tag_set');

        if (null === ($meta_tag_set = $meta_tag_set_manager->getFirst(array('id' => $id)))) {
            throw $this->createNotFoundException($translator->trans('meta_tag_set.not_found', array(), 'exception'));
        }

        $factoryService = $meta_tag_set->getFactoryService();
        if (null === ($factory = $meta_tag_set_manager->getFactory($factoryService))) {
            throw new InvalidArgumentException($translator->trans('meta_tag_set.invalid_factory', array(), 'exception'));
        }

        $meta_tag_set_form = $this->createForm(MetaTagSetType::class, $meta_tag_set);

        $meta_tag_set_form->handleRequest($request);
        if ($meta_tag_set_form->isValid()) {
            return $this->handleSave($meta_tag_set, $meta_tag_set_form);
        }

        return array(
            'page_title' => $translator->trans('meta_tag_set.edit.page_title', array(), 'backend'),
            'page_sub_title' => $meta_tag_set->getNaam(),
            'meta_tag_set' => $meta_tag_set,
            'meta_tag_set_form' => $meta_tag_set_form->createView(),
            'data_fields' => $this->container->get('visualm.tag_manager.util.extended_data_dictionary')->getAvailableFields()
        );
    }

    /**
     * Delete MetaTagSet
     *
     * @param int $id MetaTagSet Id
     *
     * @return array View Data
     */
    public function deleteAction($id)
    {
        $translator = $this->container->get('translator');
        $authChecker = $this->container->get('security.authorization_checker');

        if (!$authChecker->isGranted('ROLE_PERM_DELETE_META_TAG_SET')) {
             throw new AccessDeniedHttpException($translator->trans('meta_tag_set.access_denied', array(), 'exception'));
        }

        $meta_tag_set_manager = $this->container->get('visualm.tag_manager.manager.meta_tag_set');
        /* @var $meta_tag_set_manager MetaTagSetManager */

        if (null === ($meta_tag_set = $meta_tag_set_manager->getFirst(array('id' => $id)))) {
            throw $this->createNotFoundException($translator->trans('meta_tag_set.not_found', array(), 'exception'));
        }

        $meta_tag_set_manager->deleteItem($meta_tag_set);


        $this->addFlash(
            'success',
            $translator->trans('meta_tag_set.deleted', array(), 'flashmessage')
        );

        return $this->redirect($this->generateUrl('manage_meta_tag_set_index'));
    }

}
