from hw2 import application

def parseURL(url):
        words = url.split("/")
        if words[0] != "http:" or words[1] != "":
                print "URL should begin with http://"
                return False
        parts = words[2].split(":")
        if parts[0] != "pc110.cs.ucdavis.edu":
                print "Only handles URLs on pc110.cs.ucdavis.edu"
                return False
        try:
                machine = int(parts[1])
        except:
                print "Not a valid five-digit ID number"
                return False
        if machine < 10000 or machine > 10040:
                print "Not a valid five-digit ID number"
                return False
        if words[3] != "hw2":
                print "should be hw2 directory"
                return False
        else:
                environ = {}
                parts = words[4].split("?")
                environ["PATH_INFO"] = "/"+parts[0]
                environ["QUERY_STRING"] = parts[1] if (len(parts)>1) else ""
        return  environ

def start_response(status,headList):
        print status
        print str(headList)

def main():
        while True:
                url = raw_input("Enter url or return to exit: ")
                if url == "":
                        break
                environ = parseURL(url)
                if environ:
                        htmlList = application(environ,start_response)
                        fileName = environ["PATH_INFO"]
                        fileName = fileName[1:]
                        f = open(fileName,"w")
                        for htmlStr in htmlList:
                                f.write(htmlStr)
                        f.close()
                        print "Wrote file",fileName

                 

main()

