<?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\EventListener;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use LifeStyle\Tools\DbLogBundle\Logger\LogrotateHandler;

/**
 * Class LogrotateListener
 * @package LifeStyle\Tools\DbLogBundle\EventListener
 */
class LogrotateListener
{
    /**
     * Enable log rotate for current request
     * @var bool
     */
    private $enable;

    /**
     * Time to store values in log in seconds
     * @var int
     */
    private $storeTime;

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $entityManager;

    /**
     * LogrotateListener constructor.
     * @param Container $container
     * @param double $storeTime
     * @param int $purgeProbability
     * @throws \Exception
     */
    public function __construct(Container $container, $storeTime, $purgeProbability = 1)
    {
        $this->entityManager = $container->get('doctrine')->getManager();
        $this->enable = (rand(0, 100) < $purgeProbability * 100) && (php_sapi_name() != 'cli');
        $this->storeTime = abs($storeTime);
    }

    /**
     * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event
     */
    public function onController(FilterControllerEvent $event)
    {
        if (!$this->enable) {
            return;
        }
        $handler = new LogrotateHandler($this->entityManager);
        $handler->rotateTime(time() - $this->storeTime);
    }
}
