#!/usr/bin/env python3

import sys
import argparse
import requests
import http.server
import csv
import os.path

def make_handler_class(origin):
    class HTTPRequestHandler(http.server.BaseHTTPRequestHandler):
        def do_GET(self):
            print(self.path)
            if os.path.exists("cache" + self.path):
                f = open("cache" + self.path, "rb")
                content = f.read()
                f.close()
                self.send_response(200)
                self.end_headers()
                self.wfile.write(content)
                print("in cache")
            else:
                r = requests.get("http://" + origin + ":8080" + self.path)
                self.send_response(r.status_code)
                self.end_headers()
                self.wfile.write(r.content)
                print("from origin")

    return HTTPRequestHandler
            
def main():
    if len(sys.argv) == 5:
        parser = argparse.ArgumentParser(description="get port and origin server")
        parser.add_argument('-p', action='store')
        parser.add_argument('-o', action='store')
        args = parser.parse_args()
        args = vars(args)
        PORT = int(args['p'])
        ORIGIN = args['o']
    else:
        print("Run like: ./httpserver -p [port] -o [origin]")
        sys.exit()


    server_address = ('0.0.0.0', PORT)
    http_listen = http.server.HTTPServer(server_address, make_handler_class(ORIGIN))
    http_listen.serve_forever()


if __name__ == "__main__":
    main()
