<?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 Doctrine\ORM\EntityManagerInterface;
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 EntityManagerInterface
     */
    private $entityManager;

    /**
     * @param EntityManagerInterface $entityManager
     * @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(EntityManagerInterface $entityManager, $storeTime, $purgeProbability)
    {
        $this->entityManager = $entityManager;
        $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);
    }
}
