<?php

/**
 * @class WsLocationController
 * @author sb, mb
 *
 * 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\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Sso\Webservices\ObjectBundle\Entity;
use Sso\BackendBundle\Form;
use JMS\DiExtraBundle\Annotation\Inject;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Form\Extension\Core\Type as FormType;

/**
 * Class WsAttributesController
 * @package Sso\BackendBundle\Controller
 */
class WsAttributesController 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_attributes")
     *
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {

        $filterBuilder = $this->objectDbM()->respository()->attribute()->createQueryBuilder('a');
        $form = $this->formFactory->create(Form\WsAttributesFilterType::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_attributes/index.html.twig',
            ['form' => $form->createView(), 'pagination' => $pagination]
        );
    }

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

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

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

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

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

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

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

        return $form;
    }

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @Route("/update/{attributeId}", name="_admin_backend_webservice_attributes_update")
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $attributeId
     * @return Response|RedirectResponse
     */
    public function updateAction(Request $request, $attributeId)
    {
        $entity = $this->objectDbM()->respository()->attribute()->find($attributeId);
        if (!$entity) {
            throw $this->createNotFoundException('Attribute not found!');
        }
        $deleteForm = $this->createDeleteForm($attributeId);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $this->objectDbM()->data()->attribute()->save($entity);
            $this->get('session')->getFlashBag()->add('info', 'Attribute Saved Successfully');
            return $this->redirect(
                $this->generateUrl(
                    '_admin_backend_webservice_attributes_edit',
                    ['attributeId' => $attributeId]
                )
            );
        }

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

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

        $entity = $this->objectDbM()->respository()->attribute()->find($attributeId);

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

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

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

    /**
     * Creates a form to delete a User entity by id.
     *
     * @param string $attributeId The entity id
     * @return \Symfony\Component\Form\Form
     */
    private function createDeleteForm($attributeId)
    {
        return $this->createFormBuilder()
            ->setAction(
                $this->generateUrl(
                    '_admin_backend_webservice_attributes_delete',
                    ['attributeId' => $attributeId]
                )
            )
            ->setMethod('DELETE')
            ->add('submit', FormType\SubmitType::class, ['label' => 'Delete'])
            ->getForm();
    }
}
