# Path: amon/apps/api/utils.py
# def throttle_status(server=None):
#     result = AmonStruct()
#     result.allow = False
# 
#     last_check = server.get('last_check')
#     server_check_period = server.get('check_every', 60)
# 
#     if last_check:
#         period_since_last_check = unix_utc_now() - last_check
# 
#         # Add 15 seconds buffer, for statsd
#         period_since_last_check = period_since_last_check + 15
# 
#         if period_since_last_check >= server_check_period:
#             result.allow = True
#     else:
#         result.allow = True  # Never checked
#     
#     return result


from rest_framework.throttling import BaseThrottle
from amon.apps.servers.models import server_model
from amon.apps.api.utils import throttle_status


class CheckPeriodThrottle(BaseThrottle):
    
    def allow_request(self, request, view):
        request.server = None
        allow = True

        view_name = view.get_view_name()

        allowed_views = [u'System Data', u'Collectd Data', u'Legacy System Data']
        
        if view_name in allowed_views:
            server_key = view.kwargs.get('server_key')
            server = server_model.get_server_by_key(server_key)

            if server:

                request.server = server # Needed in the Models

# Path: amon/apps/api/utils.py
# def throttle_status(server=None):
#     result = AmonStruct()
#     result.allow = False
# 
#     last_check = server.get('last_check')
#     server_check_period = server.get('check_every', 60)
# 
#     if last_check:
#         period_since_last_check = unix_utc_now() - last_check
# 
#         # Add 15 seconds buffer, for statsd
#         period_since_last_check = period_since_last_check + 15
# 
#         if period_since_last_check >= server_check_period:
#             result.allow = True
#     else:
#         result.allow = True  # Never checked
#     
#     return result


# Path: amon/apps/api/throttle.py
from rest_framework.throttling import BaseThrottle
from amon.apps.servers.models import server_model
from amon.apps.api.utils import throttle_status



class CheckPeriodThrottle(BaseThrottle):
    
    def allow_request(self, request, view):
        request.server = None
        allow = True

        view_name = view.get_view_name()

        allowed_views = [u'System Data', u'Collectd Data', u'Legacy System Data']
        
        if view_name in allowed_views:
            server_key = view.kwargs.get('server_key')
            server = server_model.get_server_by_key(server_key)

            if server:

                request.server = server # Needed in the Models

                server_status = throttle_status(server=server)