<?php

/**
 * @class WsLanguageController
 * @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\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use JMS\DiExtraBundle\Annotation\Inject;
use Symfony\Component\Form\Form as SymfonyForm;
use Sso\Webservices\ObjectBundle\Entity;
use Sso\BackendBundle\Form;
// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * Class WsLanguageController
 * @package Sso\BackendBundle\Controller
 */
class WsLanguageController 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;

    /**
     * @Route("/", name="_admin_backend_webservice_language")
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $filterBuilder = $this->objectDbM()->respository()->language()->createQueryBuilder('a');
        $form = $this->formFactory->create(Form\WsObjectLanguageFilterType::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_language/index.html.twig',
            ['form' => $form->createView(), 'pagination' => $pagination]
        );
    }

    /**
     * @Route("/insertAllLanguagesCodes", name="_admin_backend_webservice_language_insertAllLanguagesCodes")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function insertAllLanguagesCodesAction()
    {
        try {
            $this->languageHandler()->fillLanguageWithDefaultData($this->apiM());
        } catch (\Exception $exc) {
            $this->get('session')->getFlashBag()->add('error', 'Update Languages error');
        }
        $this->get('session')->getFlashBag()->add('success', 'Language Update Success');
        return $this->redirect($this->generateUrl('_admin_backend_webservice_language'));
    }

    /**
     * @Route("/show/{languageCode}", name="_admin_backend_webservice_language_show")
     * @param string $languageCode
     * @return Response
     */
    public function showAction($languageCode)
    {
        $entityLanguage = $this->languageHandler()->getLanguageRepository()->find($languageCode);

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

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

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

    /**
     * @Route("/edit/{languageCode}", name="_admin_backend_webservice_language_edit")
     * @param string $languageCode
     * @return Response
     */
    public function editAction($languageCode)
    {
        $entity = $this->languageHandler()->getLanguageRepository()->find($languageCode);
        if (!$entity) {
            throw $this->createNotFoundException('Language not found!');
        }

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

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

    /**
     * @param Entity\Language $entity
     * @return SymfonyForm
     */
    private function createEditForm(Entity\Language $entity)
    {
        $form = $this->createForm(new Form\WsObjectLanguageType(), $entity, [
            'action' => $this->generateUrl('_admin_backend_webservice_language_update', ['id' => $entity->getId()]),
            'method' => 'PUT',
        ]);

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

        return $form;
    }

    /**
     * @Route("/edit/{id}", name="_admin_backend_webservice_language_update")
     * @param Request $request
     * @param string $id
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function updateAction(Request $request, $id)
    {
        $entity = $this->locationHandler()->getUserById($id);
        if (!$entity) {
            throw $this->createNotFoundException('User not found!');
        }
        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $this->locationHandler()->saveUser($entity);
            $this->get('session')->getFlashBag()->add('info', 'User Saved Sucess');
            return $this->redirect($this->generateUrl('_admin_backend_webservice_language_edit', array('id' => $id)));
        }
        return $this->render(
            '@SsoBackend/ws_language/edit.html.twig',
            [
                'entity' => $entity,
                'edit_form' => $editForm->createView(),
                'delete_form' => $deleteForm->createView(),
            ]
        );
    }

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

        $entity = $this->locationHandler()->getUserById($id);

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

        $this->locationHandler()->deleteUser($entity);
        $this->get('session')->getFlashBag()->add('success', 'User deleted.');

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

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

    /**
     * @return \Sso\ApiBundle\Database\Webservice\ObjectLanguage
     */
    private function languageHandler()
    {
        return $this->databaseManager()->webservice()->objectLanguage();
    }

}
