<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private 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  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\BackendBundle\Controller;

use Sso\WebserviceBundle\Entity\Webservice\Type\Attribute;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sso\BackendBundle\Form;


/**
 * Class WsApplicationAttributeController
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\BackendBundle\Controller
 */
class WsApplicationAttributeController extends WsAbstractController
{
    /**
     * @return Response
     */
    public function indexAction()
    {
        // Prepare pager
        $controller = $this;
        $routeGenerator = function ($page) use ($controller) {
            return $controller->generateUrl('_admin_backend_webservice_application_attribute', array('page' => $page));
        };
        list($filterForm, $queryBuilder) = $this->filter(
            new Form\WsApplicationAttributeFilterType(),
            $this->attributeHandler()->getAttributeRepository()
        );
        list($entities, $pagerHtml) = $this->paginator($queryBuilder, $routeGenerator);

        return $this->render('SsoBackendBundle:WsApplicationAttribute:index.html.twig', [
            'entities' => $entities,
            'pagerHtml' => $pagerHtml,
            'filterForm' => $filterForm->createView(),
        ]);
    }

    /**
     *
     * @param string $attributeId
     * @return Response
     */
    public function showAction($attributeId)
    {
        $entity = $this->attributeHandler()->getAttributeRepository()->find($attributeId);

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

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

        return $this->render('SsoBackendBundle:WsApplicationAttribute:show.html.twig', [
            'entity' => $entity,
            'delete_form' => $deleteForm->createView(),
        ]);
    }

    /**
     * @param string $attributeId
     * @return Response
     */
    public function editAction($attributeId)
    {
        $entity = $this->attributeHandler()->getAttributeById($attributeId);
        if (!$entity) {
            throw $this->createNotFoundException('Attribute not found!');
        }

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

        return $this->render('SsoBackendBundle:WsApplicationAttribute:edit.html.twig', [
            'entity' => $entity,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ]);
    }

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

        if ($editForm->isValid()) {
            $this->attributeHandler()->saveAttribute($entity);
            $this->userAppHandler()->updateAttribute($entity);
            $this->get('session')->getFlashBag()->add('info', 'Attribute Saved Sucess');

            return $this->redirect(
                $this->generateUrl(
                    '_admin_backend_webservice_application_attribute_edit',
                    ['attributeId' => $attributeId]
                )
            );
        }

        return $this->render('SsoBackendBundle:WsApplicationAttribute:edit.html.twig', array(
            'entity' => $entity,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * @return Response
     */
    public function newAction()
    {
        $entity = new Attribute($this->container->get('validator'));
        $form = $this->createCreateForm($entity);

        return $this->render('SsoBackendBundle:WsApplicationAttribute:new.html.twig', [
            'entity' => $entity,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function createAction(Request $request)
    {
        $appModel = new Attribute($this->container->get('validator'));
        $appModel->generateId();
        $form = $this->createCreateForm($appModel);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->attributeHandler()->saveAttribute($appModel);
            $this->get('session')->getFlashBag()->add('success', 'Attribute created success');

            return $this->redirect(
                $this->generateUrl(
                    '_admin_backend_webservice_application_attribute_show',
                    ['attributeId' => $appModel->getId()]
                )
            );
        }

        return $this->render('SsoBackendBundle:WsApplicationAttribute:new.html.twig', array(
            'entity' => $appModel,
            'form' => $form->createView(),
        ));
    }

    /**
     * Ajax search for attribute
     *
     * @param Request $request
     * @return JsonResponse|Response
     */
    public function searchAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            return new Response('This is no an ajax request!', 400);
        }

        $query = $request->get('query', '');
        $limit = $request->get('limit', 10);
        $offset = ($request->get('page', 1) - 1) * $limit;
        $items = array();

        $applicationId = $request->get('applicationId', '');
        $application = $this->appHandler()->getApplicationById($applicationId);

        $attributes = null !== $application ?
            $this->attributeHandler()->getAttributesByNameAndApplication($query, $application, $limit, $offset) :
            $this->attributeHandler()->getAttributesByName($query, $limit, $offset);

        foreach ($attributes as $attribute) {
            array_push($items, array(
                'id' => $attribute->getId(),
                'text' => $attribute->getName(),
            ));
        }

        $response = new JsonResponse(array(
            'total' => count($items),
            'items' => $items,
        ));
        if (null !== ($callback = $request->get('callback'))) {
            $response->setCallback($callback);
        }

        return $response;
    }

    /**
     * @param Request $request
     * @param string $attributeId
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(Request $request, $attributeId)
    {
        $form = $this->createDeleteForm($attributeId);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $entity = $this->attributeHandler()->getAttributeById($attributeId);

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

            $this->attributeHandler()->deleteAttribute($entity);
            $this->get('session')->getFlashBag()->add('success', 'Attribute deleted.');
        } else {
            $this->get('session')->getFlashBag()->add('error', 'Error while deleting attribute.');
        }

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

    /**
     * Creates a form to create an Attribute entity.
     *
     * @param Attribute $entity
     * @return \Symfony\Component\Form\Form
     */
    private function createCreateForm(Attribute $entity)
    {
        $form = $this->createForm(
            new Form\WsApplicationAttributeType(),
            $entity,
            [
                'action' => $this->generateUrl('_admin_backend_webservice_application_attribute_create'),
                'method' => 'POST',
            ]
        );

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

        return $form;
    }

    /**
     * Creates a form to edit a Attribute entity.
     *
     * @param Attribute $entity
     * @return \Symfony\Component\Form\Form
     */
    private function createEditForm(Attribute $entity)
    {
        $form = $this->createForm(
            new Form\WsApplicationAttributeType(),
            $entity,
            [
                'action' => $this->generateUrl(
                    '_admin_backend_webservice_application_attribute_update',
                    ['attributeId' => $entity->getId()]
                ),
                'method' => 'PUT',
            ]
        );

        if ($form->has('Password')) {
            $form->get('Password')->setData('');
        }

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

        return $form;
    }

    /**
     * Creates a form to delete a Application Attribute entity by id.
     *
     * @param string $attributeId
     * @return \Symfony\Component\Form\Form|\Symfony\Component\Form\FormInterface
     */
    private function createDeleteForm($attributeId)
    {
        return $this->createFormBuilder()
            ->setAction(
                $this->generateUrl('_admin_backend_webservice_application_attribute_delete',
                    array('attributeId' => $attributeId)
                )
            )
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm();
    }

    /**
     * Database handler for application attribute model
     *
     * @return \Sso\WebserviceBundle\Database\Webservice\Attribute
     */
    private function attributeHandler()
    {
        return $this->databaseManager()->webservice()->attribute();
    }

    /**
     * Database handler for application model
     *
     * @return \Sso\WebserviceBundle\Database\Webservice\Application
     */
    private function appHandler()
    {
        return $this->databaseManager()->webservice()->application();
    }

    /**
     * Database handler for user application attribute model
     *
     * @return \Sso\WebserviceBundle\Database\Webservice\UserApplicationAttribute
     */
    private function userAppHandler()
    {
        return $this->databaseManager()->webservice()->userApplicationAttribute();
    }
}
