import itertools as itt
import time
from http.server import BaseHTTPRequestHandler, HTTPServer


def _expand_steps(steps):
    return list(itt.chain(
        * [[rps] * int(duration) for rps, duration in steps]))


class RequestHandler(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        self.handlers = {
            '/stats': self._url_stats,
            '/ping': self._ping,
        }
        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

    def _url_stats(self):
        return 'application/json', b'{"instances": %d, "reqps": %d}' % (self.server.instance_counter.value, self.server.get_rps())

    def _ping(self):
        return 'text/plain', b'Pong'

    def _do_handle(self):
        if self.path not in self.handlers:
            self.send_error(404, 'Not Found')
            return
        reply = None
        try:
            reply = self.handlers[self.path]()
        except Exception as e:
            self.send_error(500, str(e))
            return
        self.send_response(200)
        if reply:
            self.send_header('Content-Type', reply[0])
            self.send_header('Content-Length', len(reply[1]))
            self.end_headers()
            self.wfile.write(reply[1])

    def do_GET(self):
        self._do_handle()

    def log_message(self, format, *args):
        pass


class StatHTTPServer(HTTPServer):

    def __init__(self, steps, instance_counter,  *args, **kwargs):
        self.instance_counter = instance_counter
        self.start_time = int(time.time())
        self.steps = _expand_steps(steps)
        HTTPServer.__init__(self, *args, **kwargs)

    def get_rps(self):
        cur_ts = int(time.time())
        offset = cur_ts - self.start_time
        reqps = 0
        if offset >= 0 and offset < len(self.steps):
            reqps = self.steps[offset]
        return reqps
