<?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 Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sso\BackendBundle\Form;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class WsUserApplicationRoleController
 * @package Sso\BackendBundle\Controller
 */
class WsUserApplicationRoleController extends WsAbstractController
{

    const TWIG_MESSAGES = "SsoBackendBundle:Layout:messages.html.twig";
    const BTN_SUBMIT = "submit";

    /**
     * Show user applications roles
     * @param string $userApplicationId
     * @return Response
     */
    public function showAction($userApplicationId)
    {
        return $this->render(
            'SsoBackendBundle:WsUserApplicationRole:show.html.twig',
            [
                'userApplication' => $this->databaseManager()->webservice()->userApplication()->getUserApplicationById($userApplicationId),
                'userApplicationRoles' => $this->getUserApplicationRoles($userApplicationId),
                'htmlUid' => uniqid('i'),
                'role_add_form' => $this->createAddForm($userApplicationId)->createView(),
                'controller' => $this,
            ]
        );
    }

    /**
     * Add users to application
     * @param Request $request
     * @param string $userApplicationId
     * @return Response
     */
    public function addAction(Request $request, $userApplicationId)
    {
        $form = $this->createAddForm($userApplicationId);
        $form->handleRequest($request);
        $formData = $form->getData();

        if ($form->isValid() && isset($formData['Roles']) && is_array($formData['Roles'])) {
            foreach ($formData['Roles'] as $roleId) {
                $this->addUserApplicationRole($userApplicationId, $roleId);
            }
        }

        return $this->render(static::TWIG_MESSAGES, array());
    }

    /**
     * Delete user from application
     * @param Request $request
     * @param string $userApplicationRoleId
     * @return Response
     */
    public function deleteAction(Request $request, $userApplicationRoleId)
    {
        $form = $this->createDeleteForm($userApplicationRoleId);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->deleteUserApplicationRole($userApplicationRoleId);
        }

        return $this->render(static::TWIG_MESSAGES, array());
    }

    /**
     * Set users application active or inactive
     * @param Request $request
     * @param string $userApplicationRoleId
     * @param bool $active
     * @return Response
     */
    public function activeAction(Request $request, $userApplicationRoleId, $active)
    {
        $form = $this->createActiveForm($userApplicationRoleId, $active);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->setUserApplicationRoleActive($userApplicationRoleId, $active);
        }

        return $this->render(static::TWIG_MESSAGES, array());
    }

    /**
     * Creates a form to add new role entities to users application
     * @param string $userApplicationId
     * @return \Symfony\Component\Form\Form The form
     */
    private function createAddForm($userApplicationId)
    {
        return $this->createForm(new Form\WsUserApplicationRoles(), array(), array(
            'action' => $this->generateUrl('_admin_backend_webservice_user_application_role_add',
                array('userApplicationId' => $userApplicationId)),
            'method' => 'POST',
        ));
    }

    /**
     * Creates a form view to delete a Application entity by id.
     * @param string $userApplicationRoleId
     * @return \Symfony\Component\Form\Form The form
     */
    public function createDeleteForm($userApplicationRoleId)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl(
                '_admin_backend_webservice_user_application_role_delete',
                array('userApplicationRoleId' => $userApplicationRoleId))
            )
            ->setMethod('DELETE')
            ->add('dummy', 'hidden')
            ->add(static::BTN_SUBMIT,
                static::BTN_SUBMIT,
                array('label' => 'Delete', 'attr' => array('class' => 'btn btn-xs btn-warning'))
            )
            ->getForm();
    }

    /**
     * Creates a form view to delete a Application entity by id.
     * @param string $userApplicationRoleId
     * @return \Symfony\Component\Form\FormView The form
     */
    public function createDeleteFormView($userApplicationRoleId)
    {
        return $this->createDeleteForm($userApplicationRoleId)->createView();
    }

    /**
     * Creates a form view to set users application active or inactive
     * @param string $userApplicationRoleId
     * @param bool $active
     *
     * @return \Symfony\Component\Form\Form The form
     */
    public function createActiveForm($userApplicationRoleId, $active)
    {
        return $this->createFormBuilder()
            ->setAction(
                $this->generateUrl(
                    '_admin_backend_webservice_user_application_role_active',
                    ['userApplicationRoleId' => $userApplicationRoleId, 'active' => $active ? 1 : 0]
                )
            )
            ->setMethod('POST')
            ->add('dummy', 'hidden')
            ->add(static::BTN_SUBMIT, static::BTN_SUBMIT, array(
                'label' => $active ? 'Set active' : 'Set inactive',
                'attr' => array('class' => 'btn btn-xs ' . ($active ? 'btn-success' : 'btn-danger')),
            ))
            ->getForm();
    }

    /**
     * Creates a form view to set users application active or inactive
     *
     * @param string $userApplicationRoleId
     * @param bool $active
     *
     * @return \Symfony\Component\Form\FormView The form
     */
    public function createActiveFormView($userApplicationRoleId, $active)
    {
        return $this->createActiveForm($userApplicationRoleId, $active)->createView();
    }

    /**
     * Set user application role active or inactive
     *
     * @param string $userApplicationRoleId
     * @param int $active
     * @return boolean
     * @throws NotFoundHttpException
     */
    private function setUserApplicationRoleActive($userApplicationRoleId, $active)
    {
        if (!($userApplicationRole = $this->databaseManager()->webservice()->userApplicationRole()->getUserApplicationRoleById($userApplicationRoleId))) {
            throw $this->createNotFoundException('User application role not found!');
        }
        $userApplicationRole->setActive($active ? 1 : 0);
        if (!$this->databaseManager()->webservice()->userApplicationRole()->saveUserApplicationRole($userApplicationRole)) {
            $this->addErrors($userApplicationRole);

            return false;
        }
        $this->addSuccess('Role "' . $userApplicationRole->getName() . '" successfully set to ' . ($active ? 'active' : 'inactive') . ' for application "' . $userApplicationRole->getUserApplication()->getName() . '"');

        return true;
    }

    /**
     * @param string $userApplicationRoleId
     * @return bool
     */
    private function deleteUserApplicationRole($userApplicationRoleId)
    {
        if (!($userApplicationRole = $this->databaseManager()->webservice()->userApplicationRole()->getUserApplicationRoleById($userApplicationRoleId))) {
            throw $this->createNotFoundException('User application role not found!');
        }
        if (!$this->databaseManager()->webservice()->userApplicationRole()->deleteUserApplicationRoles(array($userApplicationRole))) {
            $this->addErrors($userApplicationRole);

            return false;
        }
        $this->addSuccess('Role "' . $userApplicationRole->getName() . '" successfully deleted for application "' . $userApplicationRole->getUserApplication()->getName() . '"');

        return true;
    }
}
