<?php

namespace Velis\Throttling\LeakyBucket;

use Velis\App;

/**
* Cache throttling data class
*/
class CacheStorage
{
    /**
    * Sleep time
    */
    const INTERVAL = 5;

    protected static $_mode;


    public function __construct($mode = false)
    {
        self::$_mode = $mode;

        if (!$data = App::$cache[self::getCacheName()]) {
            $data = [
                'lct' =>  date('Y-m-d H:i:s'),
                'counter' => 0,
            ];
        }
        App::$cache[self::getCacheName()] = $data;
    }


    /**
    * Gets value of $name variable
    */
    public function __get($name)
    {
        $data = App::$cache[self::getCacheName()];
        return $data[$name];
    }


    /**
    * Sets variable ($name) value ($value)
    */
    public function __set($name, $value)
    {
        $data = App::$cache[self::getCacheName()];
        $data[$name] = $value;
        App::$cache[self::getCacheName()] = $data;
    }


    /**
    * Returns cache name
    */
    public static function getCacheName()
    {
        if (self::$_mode == 'public') {
            $name = $_SERVER['REMOTE_ADDR'];
        } else {
            $name =  App::$user->id();
        }

        return 'throttlingData' . $name;
    }


    /**
    * Unset cache
    */
    public static function unsetCache()
    {
        unset(App::$cache[self::getCacheName()]);
    }


    /**
    * Returns requests interval (sleep time)
    */
    public static function getInterval()
    {
        if (self::$_mode == 'public') {
            $interval = App::$config->publicActionInterval;
        } else {
            $interval = App::$config->apiActionInterval;
        }

        return $interval ?: self::INTERVAL;
    }


    /**
    * Returns max requests number
    */
    public static function getMaxContent()
    {
        if (self::$_mode == 'public') {
            $maxContent = App::$config->publicMaxRequests;
        } else {
            $maxContent = App::$config->apiMaxRequests;
        }

        return $maxContent;
    }
}
