<?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  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\BackendBundle\Controller;

use Sso\BackendBundle\Form;
use Sso\WebserviceBundle\Entity\Webservice\Type\UserGroup;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class WsUserGroupController
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\BackendBundle\Controller
 */
class WsUserGroupController extends WsAbstractController
{
    /**
     * @return Response
     */
    public function indexAction(): Response
    {
        // Prepare pager
        $controller = $this;
        $routeGenerator = function ($page) use ($controller) {
            return $controller->generateUrl('_admin_backend_webservice_user', array('page' => $page));
        };
        list($filterForm, $queryBuilder) = $this->filter(
            new Form\WsUserGroupFilterType(),
            $this->get('doctrine.orm.webservice_entity_manager')->getRepository(UserGroup::class)
        );
        list($entities, $pagerHtml) = $this->paginator($queryBuilder, $routeGenerator);

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

    /**
     * @param Request $request
     * @return Response
     */
    public function newAction(Request $request): Response
    {
        $userGroup = new UserGroup();
        $userGroup->setName('');

        $form = $this->createForm(Form\WsUserGroupType::class, $userGroup);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->get('doctrine.orm.webservice_entity_manager');
            $entityManager->persist($form->getData());
            $entityManager->flush();
            $this->addFlash('success', 'User group successfully created.');

            return $this->redirectToRoute('_admin_backend_webservice_user_group');
        }

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

    /**
     * @param int $userGroupId
     * @return Response
     */
    public function showAction(int $userGroupId): Response
    {
        $userGroup = $this->get('doctrine.orm.webservice_entity_manager')->find(UserGroup::class, $userGroupId);
        if (!$userGroup instanceof UserGroup) {
            throw $this->createNotFoundException(sprintf('User group (%d) not found in database!', $userGroupId));
        }

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

    /**
     * @param int $userGroupId
     * @param Request $request
     * @return Response
     */
    public function deleteAction(int $userGroupId, Request $request): Response
    {
        $form = $this->createUserGroupDeleteForm($userGroupId);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->get('doctrine.orm.webservice_entity_manager');
            $userGroup = $entityManager->find(UserGroup::class, $userGroupId);
            if (!$userGroup instanceof UserGroup) {
                throw $this->createNotFoundException(sprintf(
                    'User group (id %d) not found!',
                    $userGroupId
                ));
            }

            $entityManager->remove($userGroup);
            $entityManager->flush();

            $this->addFlash('success', sprintf('User-group (id %d) deleted successfully.', $userGroupId));
        }

        return $this->redirectToRoute('_admin_backend_webservice_user_group');
    }

    /**
     * @param int $userGroupId
     * @param Request $request
     * @return Response
     */
    public function editAction(int $userGroupId, Request $request): Response
    {
        $entityManager = $this->get('doctrine.orm.webservice_entity_manager');

        $userGroup = $entityManager->find(UserGroup::class, $userGroupId);
        if (!$userGroup instanceof UserGroup) {
            throw $this->createNotFoundException(sprintf(
                'User group (id %d) not found!',
                $userGroupId
            ));
        }

        $form = $this->createForm(Form\WsUserGroupType::class, $userGroup);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->get('doctrine.orm.webservice_entity_manager');
            $entityManager->persist($form->getData());
            $entityManager->flush();
            $this->addFlash('success', 'User group successfully created.');

            return $this->redirectToRoute('_admin_backend_webservice_user_group');
        }

        return $this->render('SsoBackendBundle:WsUserGroup:edit.html.twig', [
            'entity' => $userGroup,
            'form' => $form->createView(),
            'deleteForm' => $this->createUserGroupDeleteForm($userGroupId)->createView(),
        ]);
    }

    /**
     * @param int $userGroupId
     * @return \Symfony\Component\Form\Form|FormInterface
     */
    private function createUserGroupDeleteForm(int $userGroupId)
    {
        $form = $this->createFormBuilder([ 'userGroupId' => $userGroupId ]);

        $form->setAction($this->generateUrl(
            '_admin_backend_webservice_user_group_delete',
            [ 'userGroupId' => $userGroupId ]
        ));
        $form->setMethod('DELETE');
        $form->add('userGroupId', HiddenType::class);

        return $form->getForm();
    }
}
