<?php

/**
 * Class TypeMappingController
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\BackendBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use JMS\DiExtraBundle\Annotation\Inject;
use Sso\Webservices\ObjectBundle\Entity;
use Sso\BackendBundle\Form;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Form\Form as SymfonyForm;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * Class TypeMappingController
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\BackendBundle\Controller
 */
class TypeMappingController extends WsAbstractController
{
    /**
     * @Inject("form.factory")
     * @var \Symfony\Component\Form\FormFactory
     */
    private $formFactory;

    /**
     * @Inject("lexik_form_filter.query_builder_updater")
     * @var \Lexik\Bundle\FormFilterBundle\Filter\FilterBuilderUpdater
     */
    private $lexikFilterUpdater;

    /**
     * @Inject("knp_paginator")
     * @var \Knp\Component\Pager\Paginator
     */
    private $knpPaginator;

    /**
     * @Route("/", name="_admin_backend_type_mapping_index")
     *
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {

        $filterBuilder = $this->objectDbM()->respository()->typeMapping()->createQueryBuilder('a');
        $form = $this->formFactory->create(Form\TypeMappingFilterType::class);

        $reset = false;
        if ($request->query->has('filter_action') && $request->query->get('filter_action') == 'reset') {
            $reset = true;
        }
        if ($request->query->has($form->getName()) && !$reset) {
            $form->submit($request->query->get($form->getName()));
            $this->lexikFilterUpdater->addFilterConditions($form, $filterBuilder);
        }

        $query = $filterBuilder->getQuery();
        $paginator = $this->knpPaginator;
        $pagination = $paginator->paginate($query, $request->query->get('page', 1), 10);

        return $this->render(
            '@SsoBackend/type_mapping/index.html.twig',
            ['form' => $form->createView(), 'pagination' => $pagination]
        );
    }

    /**
     * @Route("/new", name="_admin_backend_type_mapping_new")
     * @return Response
     */
    public function newAction()
    {
        $entity = $this->objectDbM()->entity()->typeMapping();
        $form = $this->createCreateForm($entity);

        return $this->render(
            '@SsoBackend/type_mapping/new.html.twig',
            ['entity' => $entity, 'form' => $form->createView()]
        );
    }

    /**
     *
     * @param Entity\TypeMapping $entity
     * @return \Symfony\Component\Form\Form
     */
    private function createCreateForm(Entity\TypeMapping $entity)
    {
        $form = $this->createForm(new Form\TypeMappingType(), $entity, array(
            'action' => $this->generateUrl('_admin_backend_type_mapping_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * @Route("/create", name="_admin_backend_type_mapping_create")
     *
     * @param Request $request
     * @return Response|RedirectResponse
     */
    public function createAction(Request $request)
    {
        $entity = $this->objectDbM()->entity()->typeMapping();

        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            try {
                $this->objectDbM()->data()->typeMapping()->save($entity);
            } catch (\Exception $exc) {
                $this->get('session')->getFlashBag()->add('error', $exc->getMessage());
                return $this->redirect($this->generateUrl('_admin_backend_type_mapping_index'));
            }

            $this->get('session')->getFlashBag()->add('success', 'Type mapping has been added successfully');
            return $this->redirect($this->generateUrl('_admin_backend_type_mapping_show',
                ['identifier' => $entity->getIdentifier()]));
        }

        return $this->render(
            '@SsoBackend/type_mapping/new.html.twig',
            ['entity' => $entity, 'form' => $form->createView()]
        );
    }

    /**
     * @Route("/show/{identifier}", name="_admin_backend_type_mapping_show")
     *
     * @param string $identifier
     * @throws NotFoundHttpException
     * @return Response
     */
    public function showAction($identifier)
    {
        $entity = $this->objectDbM()->respository()->typeMapping()->find($identifier);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TypeMapping entity.');
        }

        $deleteForm = $this->createDeleteForm($identifier);

        return $this->render(
            '@SsoBackend/type_mapping/show.html.twig',
            ['entity' => $entity, 'delete_form' => $deleteForm->createView()]
        );
    }

    /**
     * @param string $identifier
     * @return SymfonyForm
     */
    private function createDeleteForm($identifier)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('_admin_backend_type_mapping_delete', ['identifier' => $identifier]))
            ->setMethod('DELETE')
            ->getForm();
    }

    /**
     * @Route("/delete/{identifier}", name="_admin_backend_type_mapping_delete")
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $identifier
     * @return RedirectResponse
     * @throws NotFoundHttpException
     */
    public function deleteAction(Request $request, $identifier)
    {
        $form = $this->createDeleteForm($identifier);
        $form->handleRequest($request);


        $entity = $this->objectDbM()->respository()->typeMapping()->find($identifier);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TypeMapping entity.');
        }
        $this->objectDbM()->data()->typeMapping()->delete($entity);
        $this->get('session')->getFlashBag()->add('success', 'TypeMapping has been deleted.');

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