import sys
import json
import datetime
import re

infile = sys.argv[1]


def GetHeader(content, code):
    return "HTTP/1.1 {0}\r\nDate:{1}\r\nServer:Fake Python Server\r\nContent-Length: {2}\r\nConnection: Closed\r\nContent-Type: text/html\r\n\r\n".format(code, datetime.datetime.now(), len(content));

def ReturnError (errorMessage, sliceA = 2, sliceB = 3):
    return { "slices" : [
        {
            "slice"         : sliceA,
            "slicePurpose"  : "Header",
            "data"          : GetHeader(errorMessage, "500 Internal Server Error") 
        },
        {
            "slice"         : sliceB,
            "slicePurpose"  : "Content",
            "data"          : errorMessage
        }
        ]}


with open(infile) as f:
    request = json.loads(f.read())

    inputSlices = request["slices"]
    headerSlice = inputSlices[0]
    contentSlice = inputSlices[1]

    p = re.compile('GET (.*) HTTP\/1.1')
    r = p.match(headerSlice["data"])
    url = r.group(0)

    responseContent = "<html><body><h1>Hello World</h1><p>Middlebox Hackathon Demo #2</p><p>You requested URL {0}</body></html>".format(url)

    response = { "slices" : [
        {
            "slice"         : headerSlice["slice"],
            "slicePurpose"  : headerSlice["slicePurpose"],
            "data"          : GetHeader(responseContent, "200 OK") 
        },
        {
            "slice"         : contentSlice["slice"],
            "slicePurpose"  : contentSlice["slicePurpose"],
            "data"          : responseContent
        }
        ]
    }

print (json.dumps(response))
