<?php

/**
 * @class WsObjectController
 * @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  2017 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\SubmitType;

/**
 * Class WsObjectController
 * @package Sso\BackendBundle\Controller
 */
class WsObjectController 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;

    /**
     * @var \Symfony\Component\HttpFoundation\File\UploadedFile
     */
    protected $file;

    /**
     * @Route("/", name="_admin_backend_webservice_object")
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $filterBuilder = $this->objectDbM()->respository()->object()->createQueryBuilder('a');
        $form = $this->formFactory->create(Form\WsObjectFilterType::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_object/index.html.twig',
            ['form' => $form->createView(), 'pagination' => $pagination]
        );
    }

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

        $connection = $em->getConnection();
        $dbPlatform = $connection->getDatabasePlatform();

        $connection->query('SET FOREIGN_KEY_CHECKS=0');

        $classMeta = $em->getClassMetadata(\Sso\Webservices\ObjectBundle\Entity\ObjectAttributeValue::class);
        $connection->executeUpdate($dbPlatform->getTruncateTableSQL($classMeta->getTableName()));

        $classMeta = $em->getClassMetadata(\Sso\Webservices\ObjectBundle\Entity\Object::class);
        $connection->executeUpdate($dbPlatform->getTruncateTableSQL($classMeta->getTableName()));

        $connection->query('SET FOREIGN_KEY_CHECKS=1');

        $this->get('session')->getFlashBag()->add('success', 'all objects deleted');
        return $this->redirect($this->generateUrl('_admin_backend_webservice_object'));
    }


    /**
     * @Route("/add/group/{objectId}", name="_admin_backend_webservice_object_add_group")
     * @param string $objectId
     * @return Response
     */
    public function addGroupAction($objectId)
    {
        $entity = $this->objectDbM()->respository()->object()->find($objectId);
        if (!$entity) {
            throw $this->createNotFoundException('Location not found!');
        }

        $form = $this->createForm(Form\WsObjectAddGroupType::class, $entity, array(
            'action' => $this->generateUrl('_admin_backend_webservice_object_update',
                array('objectId' => $entity->getGuid())),
            'method' => 'PUT',
        ));

        $form->add('submit', SubmitType::class, array('label' => 'Update'));

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

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

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

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

            $this->get('session')->getFlashBag()->add('success', 'Object created success');
            return $this->redirect($this->generateUrl('_admin_backend_webservice_object_show',
                ['objectId' => $entity->getGuid()]));
        }
        return $this->render(
            '@SsoBackend/ws_object/new.html.twig',
            ['entity' => $entity, 'form' => $form->createView()]
        );
    }

    /**
     * @param Entity\Object $entity
     * @return \Symfony\Component\Form\Form
     */
    private function createCreateForm(Entity\Object $entity)
    {
        $form = $this->createForm(Form\WsObjectType::class, $entity, array(
            'action' => $this->generateUrl('_admin_backend_webservice_object_create'),
            'method' => 'POST',
        ));

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

        return $form;
    }

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

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

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

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

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

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

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

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

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

    /**
     * @param Entity\Object $entity
     * @return SymfonyForm
     */
    private function createEditForm(Entity\Object $entity)
    {
        $form = $this->createForm(Form\WsObjectType::class, $entity, [
            'action' => $this->generateUrl('_admin_backend_webservice_object_update',
                ['objectId' => $entity->getGuid()]),
            'method' => 'PUT',
        ]);

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

        return $form;
    }

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

        if ($editForm->isValid()) {
            $this->objectDbM()->data()->object()->save($entity);
            $this->get('session')->getFlashBag()->add('info', 'Object Saved Sucess');
            return $this->redirect($this->generateUrl('_admin_backend_webservice_object_edit',
                ['objectId' => $objectId]));
        }

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

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

        $entity = $this->objectDbM()->respository()->object()->find($objectId);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Object entity.');
        }
        $this->objectDbM()->data()->object()->delete($entity);
        $this->get('session')->getFlashBag()->add('success', 'The Object was deleted successfully.');

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

    /**
     * @param string $objectId
     * @return SymfonyForm
     */
    private function createDeleteForm($objectId)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('_admin_backend_webservice_object_delete', ['objectId' => $objectId]))
            ->setMethod('DELETE')
            ->add('submit', SubmitType::class, ['label' => 'Delete'])
            ->getForm();
    }
}
