# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from twisted.internet import defer

from synapse.api.errors import LimitExceededError

from synapse.util.async import sleep
from synapse.util.logcontext import preserve_fn

import collections
import contextlib
import logging


logger = logging.getLogger(__name__)


class FederationRateLimiter(object):
    def __init__(self, clock, window_size, sleep_limit, sleep_msec,
                 reject_limit, concurrent_requests):
        """
        Args:
            clock (Clock)
            window_size (int): The window size in milliseconds.
            sleep_limit (int): The number of requests received in the last
                `window_size` milliseconds before we artificially start
                delaying processing of requests.
            sleep_msec (int): The number of milliseconds to delay processing
                of incoming requests by.
            reject_limit (int): The maximum number of requests that are can be
                queued for processing before we start rejecting requests with
                a 429 Too Many Requests response.
            concurrent_requests (int): The number of concurrent requests to
                process.
        """
        self.clock = clock

        self.window_size = window_size
        self.sleep_limit = sleep_limit
        self.sleep_msec = sleep_msec
        self.reject_limit = reject_limit
        self.concurrent_requests = concurrent_requests

        self.ratelimiters = {}

    def ratelimit(self, host):
        """Used to ratelimit an incoming request from given host

        Example usage:

            with rate_limiter.ratelimit(origin) as wait_deferred:
                yield wait_deferred
                # Handle request ...

        Args:
            host (str): Origin of incoming request.

        Returns:
            _PerHostRatelimiter
        """
        return self.ratelimiters.setdefault(