<?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\RedirectResponse;
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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\Extension\Core\Type as FormType;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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

    /**
     * @Route("/create", name="_admin_backend_webservice_attribute_group_create")
     * @param Request $request
     * @return Response|RedirectResponse
     */
    public function createAction(Request $request)
    {
        $groupModel = new Entity\AttributeGroup();

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

        if ($form->isValid()) {
            try {
                $this->groupHandler()->saveAttributeGroup($groupModel);
            } catch (\Exception $exc) {
                $this->get('session')->getFlashBag()->add('error', $exc->getMessage());
                return $this->redirect($this->generateUrl('_admin_backend_webservice_attribute_group'));
            }

            $this->get('session')->getFlashBag()->add('success', 'Attribute Group created success');
            return $this->redirect($this->generateUrl('_admin_backend_webservice_attribute_group_show',
                array('groupId' => $groupModel->getId())));
        }

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

    /**
     * @param Entity\AttributeGroup $entity
     * @return \Symfony\Component\Form\FormInterface
     */
    private function createCreateForm(Entity\AttributeGroup $entity)
    {

        $form = $this->createForm(Form\WsAttributeGroupType::class, $entity, array(
            'action' => $this->generateUrl('_admin_backend_webservice_attribute_group_create'),
            'method' => 'POST',
        ));

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

        return $form;
    }

    /**
     * @Route("/new", name="_admin_backend_webservice_attribute_group_new")
     * @return Response
     */
    public function newAction()
    {
        $entity = new Entity\AttributeGroup();
        $form = $this->createCreateForm($entity);

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

    /**
     * @Route("/show/{groupId}", name="_admin_backend_webservice_attribute_group_show")
     * @param string $groupId
     * @throws NotFoundHttpException
     * @return Response
     */
    public function showAction($groupId)
    {
        $entityTypes = $this->groupHandler()->getAttributeGroupRepository()->find($groupId);

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

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

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

    /**
     * @Route("/edit/{groupId}", name="_admin_backend_webservice_attribute_group_edit")
     * @param string $groupId
     * @throws NotFoundHttpException
     * @return Response
     */
    public function editAction($groupId)
    {
        $entity = $this->groupHandler()->getAttributeGroupById($groupId);
        if (!$entity) {
            throw $this->createNotFoundException('Type not found!');
        }

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

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

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

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

    /**
     * @Route("/update/{groupId}", name="_admin_backend_webservice_attribute_group_update")
     * @param Request $request
     * @param string $groupId
     * @return RedirectResponse|Response
     */
    public function updateAction(Request $request, $groupId)
    {
        $entity = $this->groupHandler()->getAttributeGroupById($groupId);
        if (!$entity) {
            throw $this->createNotFoundException('Attribute Group not found!');
        }
        $deleteForm = $this->createDeleteForm($groupId);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $this->groupHandler()->saveAttributeGroup($entity);
            $this->get('session')->getFlashBag()->add('info', 'Attribute Group Saved Sucess');
            return $this->redirect($this->generateUrl('_admin_backend_webservice_attribute_group_edit',
                array('groupId' => $groupId)));
        }

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

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

        $entity = $this->groupHandler()->getAttributeGroupById($groupId);

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

        $this->groupHandler()->deleteAttributeGroup($entity);
        $this->get('session')->getFlashBag()->add('success', 'Types deleted.');

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

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

    /**
     * @return \Sso\ApiBundle\Database\Webservice\AttributeGroup
     */
    private function groupHandler()
    {
        return $this->databaseManager()->webservice()->attributeGroup();
    }
}
