<?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 LifeStyle\Tools\DbLogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\View\TwitterBootstrap3View;
use LifeStyle\Tools\DbLogBundle\Entity;
use LifeStyle\Tools\DbLogBundle\Form;

/**
 * Class SystemLogController
 * @package LifeStyle\Tools\DbLogBundle\Controller
 */
class SystemLogController extends Controller
{
    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
        $this->disableLog();
        list($filterForm, $queryBuilder) = $this->filter();
        // Add default order
        $queryBuilder->orderBy('e.createdTime', 'DESC');
        list($entities, $pagerHtml) = $this->paginator($queryBuilder);
        return $this->render('LifeStyleToolsDbLogBundle:SystemLog:index.html.twig', array(
            'entities' => $entities,
            'pagerHtml' => $pagerHtml,
            'filterForm' => $filterForm->createView(),
        ));
    }

    /**
     * Delete log
     */
    public function deleteAction()
    {
        $this->disableLog();
        $classMeta = $this->getDoctrine()->getManager()->getClassMetadata('LifeStyle\Tools\DbLogBundle\Entity\SystemLog');
        $classMetaData = $this->getDoctrine()->getManager()->getClassMetadata('LifeStyle\Tools\DbLogBundle\Entity\SystemLogData');
        $connection = $this->getDoctrine()->getManager()->getConnection(); // This only works with default connection
        $dbPlatform = $connection->getDatabasePlatform();
        $connection->query('SET FOREIGN_KEY_CHECKS=0');
        $connection->executeUpdate($dbPlatform->getTruncateTableSql($classMeta->getTableName()));
        $connection->executeUpdate($dbPlatform->getTruncateTableSql($classMetaData->getTableName()));
        $connection->query('SET FOREIGN_KEY_CHECKS=1');
        return $this->redirect($this->generateUrl('_life_style_tools_db_log_overview'));
    }

    /**
     * @return array
     */
    protected function filter()
    {
        $request = $this->getRequest();
        $session = $request->getSession();
        $filterForm = $this->createForm(new Form\LogFilterType());
        //$queryBuilder = $this->userHandler()->getUserRepository()->createQueryBuilder('e');
        $queryBuilder = $this->getDoctrine()->getManager()->getRepository('LifeStyle\Tools\DbLogBundle\Entity\SystemLog')->createQueryBuilder('e');
        // Reset filter
        if ($request->get('filter_action') == 'reset') {
            $session->remove('LogControllerFilter');
        }

        // Filter action
        if ($request->get('filter_action') == 'filter') {
            // Bind values from the request
            $filterForm->bind($request);

            if ($filterForm->isValid()) {
                // Build the query from the given form object
                $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
                // Save filter to session
                $filterData = $filterForm->getData();
                $session->set('LogControllerFilter', $filterData);
            }
        } else {
            // Get filter from session
            if ($session->has('LogControllerFilter')) {
                $filterData = $session->get('LogControllerFilter');
                $filterForm = $this->createForm(new Form\LogFilterType(), $filterData);
                $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
            }
        }

        return array($filterForm, $queryBuilder);
    }

    /**
     * @param $queryBuilder
     * @return array
     */
    protected function paginator($queryBuilder)
    {
        // Paginator
        $adapter = new DoctrineORMAdapter($queryBuilder, false, false);
        $pagerfanta = new Pagerfanta($adapter);
        $pagerfanta->setMaxPerPage(10);
        $currentPage = $this->getRequest()->get('page', 1);
        $pagerfanta->setCurrentPage($currentPage);

        $entities = $pagerfanta->getCurrentPageResults();
        // Paginator - route generator
        $controller = $this;
        $routeGenerator = function ($page) use ($controller) {
            return $controller->generateUrl('_life_style_tools_db_log_overview', array('page' => $page));
        };

        // Paginator - view
        $translator = $this->get('translator');
        $view = new TwitterBootstrap3View();
        $pagerHtml = $view->render($pagerfanta, $routeGenerator, array(
            'proximity' => 3,
            'prev_message' => $translator->trans('prev', array(), 'JordiLlonchCrudGeneratorBundle'),
            'next_message' => $translator->trans('next', array(), 'JordiLlonchCrudGeneratorBundle'),
        ));

        return array($entities, $pagerHtml);
    }

    /**
     * Disable all loggers
     */
    protected function disableLog()
    {
        foreach (array('monolog.logger.doctrine', 'logger') as $service) {
            $logger = $this->get($service);
            $logger->pushHandler(new \Monolog\Handler\NullHandler());
        }
    }
}
