<?php

/**
 *
 * @class WsLocationController
 * @author sb
 *
 * 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  2015 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @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;
use Symfony\Component\Form\Extension\Core\Type as FormType;

/**
 * Class WsTypeController
 * @package Sso\BackendBundle\Controller
 */
class WsTypeController 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_webservice_type")
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $filterBuilder = $this->objectDbM()->respository()->type()->createQueryBuilder('a');
        $form = $this->formFactory->create(Form\WsTypeFilterType::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/ws_type/index.html.twig',
            ['form' => $form->createView(), 'pagination' => $pagination]
        );
    }

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

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

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

            $this->get('session')->getFlashBag()->add('success', 'Type created success');
            return $this->redirect($this->generateUrl('_admin_backend_webservice_type_show',
                ['typeId' => $entity->getId()]));
        }

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

    /**
     * @param Entity\Type $entity
     * @return SymfonyForm
     */
    private function createCreateForm(Entity\Type $entity)
    {
        $form = $this->createForm(Form\Type::class, $entity, [
            'action' => $this->generateUrl('_admin_backend_webservice_type_create'),
            'method' => 'POST',
        ]);

        $form->add('submit', FormType\SubmitType::class, ['label' => 'Create']);

        return $form;
    }

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

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

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

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

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

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

    /**
     * @Route("/edit/{typeId}", name="_admin_backend_webservice_type_edit")
     * @param string $typeId
     * @throws NotFoundHttpException
     * @return Response
     */
    public function editAction($typeId)
    {
        $entity = $this->objectDbM()->respository()->type()->find($typeId);
        if (!$entity) {
            throw $this->createNotFoundException('Type not found!');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($typeId);

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

    /**
     * @param Entity\Type $entity
     * @return \Symfony\Component\Form\Form
     */
    private function createEditForm(Entity\Type $entity)
    {
        $form = $this->createForm(Form\Type::class, $entity, array(
            'action' => $this->generateUrl('_admin_backend_webservice_type_update', ['typeId' => $entity->getId()]),
            'method' => 'PUT',
        ));

        $form->add('submit', FormType\SubmitType::class, ['label' => 'Update']);

        return $form;
    }

    /**
     * @Route("/update/{typeId}", name="_admin_backend_webservice_type_update")
     * @param Request $request
     * @param string $typeId
     * @return Response|RedirectResponse
     */
    public function updateAction(Request $request, $typeId)
    {
        $entity = $this->objectDbM()->respository()->type()->find($typeId);
        if (!$entity) {
            throw $this->createNotFoundException('Location not found!');
        }
        $deleteForm = $this->createDeleteForm($typeId);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $this->objectDbM()->data()->type()->save($entity);
            $this->get('session')->getFlashBag()->add('info', 'Type Saved Sucess');
            return $this->redirect($this->generateUrl('_admin_backend_webservice_type_edit',
                array('typeId' => $typeId)));
        }

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

    /**
     * @Route("/delete/all", name="_admin_backend_webservice_type_delete_all")
     * @param Request $request
     * @return RedirectResponse
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAllAction(Request $request)
    {
        set_time_limit(0);
        $em = $this->objectDbM()->entityManager();

        $types = $this->objectDbM()->respository()->type()->findAll();
        foreach ($types as $type) {

            if (count($type->getObjects()) > 0) {
                foreach ($type->getObjects() as $object) {
                    $em->remove($object);
                    $em->flush($object);
                }
            }

            if (count($type->getAttributeGroups()) > 0) {
                foreach ($type->getAttributeGroups() as $attributeGroup) {

                    if (count($attributeGroup->getAttributes()) > 0) {
                        foreach ($attributeGroup->getAttributes() as $attribute) {
                            $em->remove($attribute);
                            $em->flush($attribute);
                        }
                    }

                    $em->remove($attributeGroup);
                    $em->flush($attributeGroup);
                }
            }

            $em->remove($type);
            $em->flush($type);
        }
        $this->get('session')->getFlashBag()->add('success', 'all types deleted');
        return $this->redirect($this->generateUrl('_admin_backend_webservice_type'));
    }

    /**
     * @Route("/delete/{typeId}", name="_admin_backend_webservice_type_delete")
     *
     * @param Request $request
     * @param string $typeId
     *
     * @throws NotFoundHttpException
     * @return RedirectResponse
     */
    public function deleteAction(Request $request, $typeId)
    {
        $form = $this->createDeleteForm($typeId);
        $form->handleRequest($request);
        $entity = $this->objectDbM()->respository()->type()->find($typeId);

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

        $this->objectDbM()->data()->type()->delete($entity);
        $this->get('session')->getFlashBag()->add('success', 'Type deleted.');

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

    /**
     * @param string $typeId
     * @return \Symfony\Component\Form\FormInterface
     */
    private function createDeleteForm($typeId)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('_admin_backend_webservice_type_delete', ['typeId' => $typeId]))
            ->setMethod('DELETE')
            ->add('submit', FormType\SubmitType::class, ['label' => 'Delete'])
            ->getForm();
    }
}
