<?php

namespace Velis\Throttling\LeakyBucket;

use Velis\App;
use User\AuthLog;

/**
* Database throttling data class
*/
class DatabaseStorage
{
    /**
    * Sleep time
    */
    const INTERVAL = 10;

    protected $_data;

    public function __construct()
    {
        if (!isset($this->_data)) {
            $params = [
                'user_auth_action_id' => 'FailedLogin',
                'ip_address' => $_SERVER['REMOTE_ADDR'],
                'last_hour' => 1,
            ];
            $this->_data = AuthLog::listAll($params) ?: [];
        }
    }


    /**
    * Gets value of $name variable
    */
    public function __get($name)
    {
        if (!isset($this->_data)) {
            $params = [
                'user_auth_action_id' => 'FailedLogin',
                'ip_address' => $_SERVER['REMOTE_ADDR'],
                'last_hour' => 1,
            ];
            $this->_data = AuthLog::listAll($params) ?: [];
        }

        if ($name == 'lct') {
            return reset($this->_data)['date_added'] ?: date('Y-m-d H:i:s');
        } else {
            return count($this->_data);
        }
    }


    /**
    * Returns requests interval (sleep time)
    */
    public static function getInterval()
    {
        return App::$config->loginActionInterval ?: self::INTERVAL;
    }


    /**
    * Returns max requests number
    */
    public static function getMaxContent()
    {
        return App::$config->loginMaxRequests;
    }
}
