import json
import sys
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn

import infra.yp_service_discovery.api.api_pb2 as api


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        assert self.path == '/resolve_endpoints'

        content_length = int(self.headers['Content-Length'])
        request = api.TReqResolveEndpoints()
        request.ParseFromString(self.rfile.read(content_length))

        backends = self.backends.get((request.cluster_name, request.endpoint_set_id))
        if backends is None:
            backends = self.backends.get('_')
        if backends is None:
            raise Exception('Unknown endpoint set')

        response = api.TRspResolveEndpoints()
        response.timestamp = 1

        for backend in backends:
            ep = response.endpoint_set.endpoints.add()
            ep.fqdn = backend['ip']
            ep.ip4_address = backend['ip']
            ep.port = backend['port']
            ep.ready = backend.get('ready', True)

        self.send_response(200)
        self.end_headers()

        self.wfile.write(response.SerializeToString())

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


class Server(ThreadingMixIn, HTTPServer):
    allow_reuse_address = True


def main():
    port = int(sys.argv[1])

    backends_param = {}
    for endpoint_set in json.load(open(sys.argv[2], 'r')):
        if endpoint_set['cluster_name'] == '_' and endpoint_set['endpoint_set_id'] == '_':
            backends_param['_'] = endpoint_set['backends']
        else:
            backends_param[(endpoint_set['cluster_name'], endpoint_set['endpoint_set_id'])] = endpoint_set['backends']

    class HandlerWithBackends(Handler):
        backends = backends_param

    server = Server(('127.0.0.1', port), HandlerWithBackends)
    server.serve_forever()
