<?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\WebserviceBundle\Logger\TokenUsage;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

/**
 * Class LogrotateListener
 * @package Sso\WebserviceBundle\Logger\TokenUsage
 */
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;

    /**
     * @var boolean
     */
    private $readonly;

    /**
     * @param ContainerInterface $container
     * @param boolean $readonly
     * @param int $storeTime Time in seconds, log entries will be kept
     * @param int $purgeProbability Probability (value between 0 and 1) to clean up
     */
    public function __construct(ContainerInterface $container, $readonly, $storeTime, $purgeProbability = 1)
    {
        $this->entityManager = $container->get('doctrine')->getManager('ServiceProvider');
        $this->readonly = (boolean)$readonly;
        $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, $this->readonly);
        $handler->rotateTime(time() - $this->storeTime);
    }
}
