
from __future__ import absolute_import

import logging

from vdsm.common.time import monotonic_time

_DEFAULT_TIMEOUT_SEC = 3600

_logger = logging.getLogger('throttled')

_periodic = {}


class _Periodic(object):

    def __init__(self, interval, timeout):
        self._interval = interval
        self._timeout = timeout
        self._counter = 0
        self._last_time = 0

    def tick(self):
        now = monotonic_time()
        result = self._result(now)
        self._counter = (self._counter + 1) % self._interval
        if result:
            self._last_time = now
        return result

    def _result(self, now):
        return (self._counter == 0 or
                (now - self._last_time) >= self._timeout)


def throttle(name, interval, timeout=_DEFAULT_TIMEOUT_SEC):
    _periodic[name] = _Periodic(interval, timeout)


def log(name, level, message, *args):
    try:
        periodic = _periodic[name]
    except KeyError:
    else:
        if not periodic.tick():
            return

    _logger.log(level, message, *args)


def debug(name, message, *args):
    log(name, logging.DEBUG, message, *args)


def info(name, message, *args):
    log(name, logging.INFO, message, *args)


def warning(name, message, *args):
    log(name, logging.WARNING, message, *args)
