<?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\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sso\BackendBundle\Form;

/**
 * Class WsUserApplicationController
 * @package Sso\BackendBundle\Controller
 */
class WsUserApplicationController extends WsAbstractController
{
    /**
     * List applications users
     * @param string $applicationId
     * @return Response
     */
    public function userShowAction($applicationId)
    {
        if (!($application = $this->databaseManager()->webservice()->application()->getApplicationById($applicationId))) {
            throw $this->createNotFoundException('Unable to find Application entity.');
        }

        return $this->render(
            'SsoBackendBundle:WsUserApplication:user.html.twig',
            [
                'application' => $application,
                'user_add_form' => $this->createUserAddForm($applicationId)->createView(),
                'controller' => $this,
                'htmlUid' => uniqid('i'),
            ]
        );
    }

    /**
     * List users applications
     * @param string $userId
     * @return Response
     */
    public function applicationShowAction($userId)
    {
        if (!($user = $this->databaseManager()->webservice()->user()->getUserById($userId))) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        return $this->render(
            'SsoBackendBundle:WsUserApplication:application.html.twig',
            [
                'user' => $user,
                'application_add_form' => $this->createApplicationAddForm($userId)->createView(),
                'controller' => $this,
                'htmlUid' => uniqid('i'),
            ]
        );
    }

    /**
     * Add users to application
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $applicationId
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function userAddAction(Request $request, $applicationId)
    {
        $form = $this->createUserAddForm($applicationId);
        $form->handleRequest($request);
        $formData = $form->getData();

        if ($form->isValid() && isset($formData['Users'])) {
            foreach ($formData['Users'] as $userId) {
                $this->addUserApplication($applicationId, $userId);
            }
        } else {
            $this->addFlash('error', 'Invalid request');
        }

        return $this->render('SsoBackendBundle:Layout:messages.html.twig', array());
    }

    /**
     * Delete user from application
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $applicationId
     * @param string $userId
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function userDeleteAction(Request $request, $applicationId, $userId)
    {
        $form = $this->createUserDeleteForm($applicationId, $userId);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->deleteUserApplication($applicationId, $userId);
        }

        return $this->render('SsoBackendBundle:Layout:messages.html.twig', array());
    }

    /**
     * Set users application active or inactive
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $applicationId
     * @param string $userId
     * @param bool $active
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function userActiveAction(Request $request, $applicationId, $userId, $active)
    {
        $form = $this->createUserActiveForm($applicationId, $userId, $active);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->setUserApplicationActive($applicationId, $userId, $active);
        }

        return $this->render('SsoBackendBundle:Layout:messages.html.twig', array());
    }

    /**
     * Add applications to user
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $userId
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function applicationAddAction(Request $request, $userId)
    {
        $form = $this->createApplicationAddForm($userId);
        $form->handleRequest($request);
        $formData = $form->getData();

        if ($form->isValid() && isset($formData['Applications']) && is_array($formData['Applications'])) {
            foreach ($formData['Applications'] as $applicationId) {
                $this->addUserApplication($applicationId, $userId);
            }
        }

        return $this->render('SsoBackendBundle:Layout:messages.html.twig', array());
    }

    /**
     * Delete application from user
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $userId
     * @param string $applicationId
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function applicationDeleteAction(Request $request, $userId, $applicationId)
    {
        $form = $this->createApplicationDeleteForm($userId, $applicationId);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->deleteUserApplication($applicationId, $userId);
        }

        return $this->render('SsoBackendBundle:Layout:messages.html.twig', array());
    }

    /**
     * Set users application active or inactive
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $userId
     * @param string $applicationId
     * @param bool $active
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function applicationActiveAction(Request $request, $userId, $applicationId, $active)
    {
        $form = $this->createApplicationActiveForm($userId, $applicationId, $active);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->setUserApplicationActive($applicationId, $userId, $active);
        }

        return $this->render('SsoBackendBundle:Layout:messages.html.twig', array());
    }

    /**
     * Creates a form to add new user entities to application
     * @param string $applicationId
     * @return \Symfony\Component\Form\Form The form
     */
    private function createUserAddForm($applicationId)
    {
        return $this->createForm(
            Form\WsApplicationUsers::class,
            null,
            array(
                'action' => $this->generateUrl(
                    '_admin_backend_webservice_user_application_user_add',
                    array('applicationId' => $applicationId)
                ),
                'method' => 'POST',
            )
        );
    }

    /**
     * Creates a form view to delete a Application entity by id.
     * @param string $applicationId
     * @param string $userId
     * @return \Symfony\Component\Form\Form The form
     */
    public function createUserDeleteForm($applicationId, $userId)
    {
        return $this->createFormBuilder()
            ->setAction(
                $this->generateUrl(
                    '_admin_backend_webservice_user_application_user_delete',
                    array('applicationId' => $applicationId, 'userId' => $userId)
                )
            )
            ->setMethod('DELETE')
            ->add('dummy', 'hidden')
            ->add('submit', '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 $applicationId
     * @param string $userId
     * @return \Symfony\Component\Form\FormView The form
     */
    public function createUserDeleteFormView($applicationId, $userId)
    {
        return $this->createUserDeleteForm($applicationId, $userId)->createView();
    }

    /**
     * Creates a form view to set users application active or inactive
     * @param string $applicationId
     * @param string $userId
     * @param bool $active
     * @return \Symfony\Component\Form\Form The form
     */
    public function createUserActiveForm($applicationId, $userId, $active)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl(
                '_admin_backend_webservice_user_application_user_active',
                array(
                    'applicationId' => $applicationId,
                    'userId' => $userId,
                    'active' => $active ? 1 : 0,
                )))
            ->setMethod('POST')
            ->add('dummy', 'hidden')
            ->add('submit', '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 $applicationId
     * @param string $userId
     * @param bool $active
     * @return \Symfony\Component\Form\FormView The form
     */
    public function createUserActiveFormView($applicationId, $userId, $active)
    {
        return $this->createUserActiveForm($applicationId, $userId, $active)->createView();
    }

    /**
     * Creates a form to add new user entities to application
     * @param string $userId
     * @return \Symfony\Component\Form\Form The form
     */
    private function createApplicationAddForm($userId)
    {
        return $this->createForm(new Form\WsUserApplications(), array(), array(
            'action' => $this->generateUrl(
                '_admin_backend_webservice_user_application_application_add',
                array('userId' => $userId)),
            'method' => 'POST',
        ));
    }

    /**
     * Creates a form to delete a Application from user
     * @param string $userId
     * @param string $applicationId
     * @return \Symfony\Component\Form\Form The form
     */
    public function createApplicationDeleteForm($userId, $applicationId)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl(
                '_admin_backend_webservice_user_application_application_delete',
                array('userId' => $userId, 'applicationId' => $applicationId)))
            ->setMethod('DELETE')
            ->add('dummy', 'hidden')
            ->add('submit', 'submit', array('label' => 'Delete', 'attr' => array('class' => 'btn btn-xs btn-warning')))
            ->getForm();
    }

    /**
     * Creates a form view to set users application active or inactive
     * @param string $userId
     * @param string $applicationId
     * @param bool $active
     * @return \Symfony\Component\Form\Form The form
     */
    public function createApplicationActiveForm($userId, $applicationId, $active)
    {
        return $this->createFormBuilder()
            ->setAction(
                $this->generateUrl(
                    '_admin_backend_webservice_user_application_application_active',
                    array(
                        'userId' => $userId,
                        'applicationId' => $applicationId,
                        'active' => $active ? 1 : 0,
                    )
                )
            )
            ->setMethod('POST')
            ->add('dummy', 'hidden')
            ->add('submit', '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 $userId
     * @param string $applicationId
     * @param bool $active
     * @return \Symfony\Component\Form\FormView The form
     */
    public function createApplicationActiveFormView($userId, $applicationId, $active)
    {
        return $this->createApplicationActiveForm($userId, $applicationId, $active)->createView();
    }

    /**
     * Creates a form view to delete a Application from user
     * @param string $userId
     * @param string $applicationId
     * @return \Symfony\Component\Form\FormView The form
     */
    public function createApplicationDeleteFormView($userId, $applicationId)
    {
        return $this->createApplicationDeleteForm($userId, $applicationId)->createView();
    }
}
