<?php

namespace Comitium5\DesignerBundle\Controller\Template;

use Comitium5\DesignerBundle\Controller\CRUDController;
use Comitium5\DesignerBundle\Entity\Template;
use Comitium5\DesignerBundle\Form\Type\SearchFormType;
use Comitium5\DesignerBundle\Form\Type\Template\TemplateType;
use Comitium5\DesignerBundle\Resolver\Template\TemplateTreeResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class TemplateController
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Controller\Template
 */
class TemplateController extends CRUDController
{
    /**
     * @param Request $request
     *
     * @return mixed|\Symfony\Component\HttpFoundation\RedirectResponse|Response
     * @throws \Exception
     */
    public function listAction(Request $request)
    {
        $this->checkRequest($request);

        $templates = $this->get('designer.repository.template')->findAll();

        $templatesTree = TemplateTreeResolver::resolve($templates);

        return $this
            ->render(
                "Comitium5DesignerBundle:Template:page.html.twig",
                [
                    'templates' => $templatesTree
                ]
            );
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     * @throws \Exception
     */
    public function searchAction(Request $request)
    {
        $masterRequest = $this->get('request_stack')->getMasterRequest();

        $this->checkRequest($request);

        $builder = $this->get('designer.manager.search.search_list')->handleSimpleSearch(
            $this->get('designer.repository.template'),
            $request
        );

        $form = $this->createForm(SearchFormType::class, null, [
            'method' => $request->getMethod(),
        ]);

        $form->handleRequest($request);

        $searchForm = $form->get('search')->getData();
        $searchRequest = $masterRequest->query->get('admin_search')['search'];

        if (empty($searchForm) || empty($searchRequest)) {
            if ($request->isXmlHttpRequest() && empty($searchForm)) {

                return $this->redirect($this->generateUrl("designer_template_index"));
            } elseif (empty($searchRequest)) {
                return $this->forward("AdminBundle:Template/Template:list");
            }
        }

        return $this->render('AdminBundle:Template:search-list.html.twig', [
            'entities' => $builder->getQuery()->getResult(),
        ]);
    }

    /**
     * @param Request $request
     *
     * @return TemplateController|mixed|\Symfony\Component\HttpFoundation\RedirectResponse|Response
     * @throws \Doctrine\ORM\ORMException
     */
    public function createAction(Request $request)
    {
        $manager = $this->get('designer.manager.template');

        $entity = $manager->getFactory()->create();

        $form = $this->createForm(TemplateType::class, $entity, array(
            'method' => Request::METHOD_POST,
            'validation_groups' => 'new',
            'data_class' => $manager->getFactory()->getEntityNamespace(),
        ));

        $form->handleRequest($request);

        if ($form->isValid()) {
            $success = $manager->save($entity);

            if ($success !== false) {
                $this->addToastrMessage('success', 'admin_template.create.messages.success.create');
            } else {
                $this->addToastrMessage('error', 'admin_template.create.messages.error.create');
            }

            return $this->handleFormRedirect($form, $this->generateUrl('designer_template_index'));
        }

        return $this->render('Comitium5DesignerBundle:Template:form.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

    /**
     * @param Request $request
     * @param Template|null $entity
     *
     * @return TemplateController|mixed|\Symfony\Component\HttpFoundation\RedirectResponse|Response
     * @throws \Doctrine\ORM\ORMException
     */
    public function editAction(Request $request, Template $entity = null)
    {
        $manager = $this->get('designer.manager.template');

        $form = $this->createForm(TemplateType::class, $entity, array(
            'method' => Request::METHOD_POST,
            'validation_groups' => 'edit',
            'data_class' => Template::class,
        ));

        $form->handleRequest($request);

        if ($form->isValid()) {
            $success = $manager->update($entity);

            if ($success !== false) {
                $this->addToastrMessage('success', 'admin_template.create.messages.success.edit');
            } else {
                $this->addToastrMessage('error', 'admin_template.create.messages.error.edit');
            }

            return $this->handleFormRedirect($form, $this->generateUrl('designer_template_index'));
        }

        return $this->render('@Comitium5Designer/Template/form.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

    /**
     * @param Request $request
     * @param Template|null $entity
     *
     * @return mixed|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function deleteAction(Request $request, Template $entity = null)
    {
        if ($request->isMethod(Request::METHOD_GET)) {
            if ($this->get("designer.manager.template")->checkDeletion($entity) === false) {
                $title   = $this->get('translator')->trans('template_admin.form.delete.has_associations_title');
                $message = $this->get('translator')->trans('template_admin.form.delete.has_associations_message');

                return $this->responseAvoidDeletion($title, $message);
            }

            return new Response();
        }

        if (!$entity) {
            return $this->redirectToRoute('designer_template_index');
        }

        $success = $this->get('designer.manager.template')->remove($entity);

        if ($success !== false) {
            $this->addToastrMessage('success', 'template_admin.create.messages.success.delete');
        } else {
            $this->addToastrMessage('error', 'template_admin.create.messages.error.delete');
        }

        return $this->redirectToRoute('designer_template_index');
    }
}
