<?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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sso\BackendBundle\Form;
use Sso\WebserviceBundle\Entity\ServiceProvider\Type\TokenUsage;

/**
 * Class TokenUsageController
 * @package Sso\BackendBundle\Controller
 */
class TokenUsageController extends WsAbstractController
{
    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
        // Prepare pager
        $controller = $this;
        $routeGenerator = function ($page) use ($controller) {
            return $controller->generateUrl('_admin_backend_tokenusage_index', array('page' => $page));
        };
        list($filterForm, $queryBuilder) = $this->filter(
            new Form\TokenUsageFilterType(),
            $this->tokenUsageHandler()->getRepository()
        );
        list($entities, $pagerHtml) = $this->paginator($queryBuilder, $routeGenerator);

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

    /**
     * @Route("/", name="_admin_backend_tokenusage_delete")
     */
    public function deleteAction()
    {
        $classMeta = $this->getDoctrine()->getManager('ServiceProvider')->getClassMetadata(TokenUsage::class);
        $connection = $this->getDoctrine()->getManager('ServiceProvider')->getConnection('ServiceProvider');
        $dbPlatform = $connection->getDatabasePlatform();
        $connection->query('SET FOREIGN_KEY_CHECKS=0');
        $connection->executeUpdate($dbPlatform->getTruncateTableSql($classMeta->getTableName()));
        $connection->query('SET FOREIGN_KEY_CHECKS=1');

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

    /**
     * @return \Sso\WebserviceBundle\Database\ServiceProvider\TokenUsage Database handler for TokenUsage model
     */
    private function tokenUsageHandler()
    {
        return $this->databaseManager()->serviceProvider()->tokenUsage();
    }
}
