#!/usr/bin/env python2.7
# -*- python -*-

import BaseHTTPServer as httpserver
import SimpleHTTPServer as simplehttpserver
import SocketServer as socketserver
import threading
import os, os.path, posixpath

class ThreadedHTTPServer(socketserver.ThreadingMixIn, httpserver.HTTPServer):
    """Handle requests in a separate thread."""

class FileServer(simplehttpserver.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_no_cache()
        simplehttpserver.SimpleHTTPRequestHandler.end_headers(self)

    def send_no_cache(self):
        self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
        self.send_header("Pragma", "no-cache")
        self.send_header("Expires", "0")
        self.send_header("Accept-Ranges", "none")

    def translate_path(self, path):
        import urllib

        path = path.split('?',1)[0]
        path = path.split('#',1)[0]
        trailing_slash = True if path.rstrip().endswith('/') else False
        path = posixpath.normpath(urllib.unquote(path))
        words = path.split('/')
        words = filter(None, words)
        path = self.server.base_directory

        for word in words:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir, os.pardir): continue
            path = os.path.join(path, word)

        if trailing_slash:
            path += '/'

        return path

class AppServer(threading.Thread):
    def __init__(self, host, port, directory):
        self.host = host
        self.port = int(port)
        self.server = ThreadedHTTPServer(
            (host, port),
            FileServer)
        self.server.base_directory = directory
        threading.Thread.__init__(self)

    def run(self):
        self.server.serve_forever()

    def stop(self):
        self.server.shutdown()

class QmlRunner:
    def __init__(self, app_dir):
        import sys

        self.server = AppServer("0.0.0.0", 8080, app_dir)
        self.server.start()

    def stop(self):
        print 'Stopping HTTP server'
        self.server.stop()

def main():
    app_directory = os.path.dirname(".")
    runner = QmlRunner(app_directory)

    while True:
        try:
            raw_input()
        except (KeyboardInterrupt, EOFError):
            break

    print "Exitting"

    runner.stop()

if __name__ == '__main__':
    main()
