#!/usr/bin/python

import time,threading,os,sys,re,shutil,mimetypes
import BaseHTTPServer
import SocketServer
"""HTTP
"""
class RequestHandler(SocketServer.ThreadingMixIn,
                     BaseHTTPServer.BaseHTTPRequestHandler,
                     ):

    def do_HEAD(self):
        print self.path
        print self.headers
        print self.headers.getheader('content-type')
        print self.headers.getheader('content-length')


    def do_GET(self):
        self.do_HEAD()
        if '/api/' in self.path:
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write('{}');
        else:
	    path = 'index.html'
            if not os.path.isfile(path) or not os.access(path, os.R_OK):
                self.send_error(404, "file not found")
                return None

            content, encoding = mimetypes.MimeTypes().guess_type(path)
            if content is None:
                content = "application/octet-stream"

            info = os.stat(path)

            self.send_response(200)
            self.send_header("Content-Type", content)
            self.send_header("Content-Encoding", encoding)
            self.send_header("Content-Length", info.st_size)
            self.end_headers()
            f = open(path, 'rb')
            shutil.copyfileobj(f, self.wfile)
            f.close()

    def do_POST(self):
        self.do_HEAD()
        print self.rfile
        self.send_response(200)
        self.end_headers()

class HtmlRestServer(object):
    def __init__(self,funcLst):
	self.server = BaseHTTPServer.HTTPServer(('', 57005), RequestHandler)
        self.thread = threading.Thread(target = self.server.serve_forever)
        self.thread.daemon = True
        self.thread.start()

"""THREAD
"""
class Thread(object):
    def __init__(self,functor, timing=0.1):
        self.online = True
        self.functor = functor
        def timeloop():
            print("thread initiated at "+str(1/timing)+" tick every seconds")
            while True:
                try:
                    if self.online:
                        if self.functor:
                            self.functor = self.functor()
                        else:
                            self.online = None
                    else:
                        time.sleep(0.25)
                except Exception as e:
                    print e
                    print 'wait a sec'
                    time.sleep(1)
                time.sleep(timing)
        self.timethread = threading.Thread(target = timeloop)
        self.timethread.daemon = True
        self.timethread.start()

    def stop(self):
        self.online = False

    def start(self):
        self.online = True

"""ADMIN
"""
def admin(threadLst=[]):
    cli = []
    def _help():
        for name,_,how in cli:
            if how:
                print name,how
    cli.append(('help',_help," => show this"))
    def _play():
        import webbrowser
        webbrowser.open('localhost:57005/www/main.html',2,True)
        print "webbrowser triggered"
    cli.append(('play',_play," => start game"))
    def _restart():
        print("""restart""")
        os.execl(sys.executable, sys.executable, * sys.argv)
    cli.append(('restart', _restart," => restart the whole server"))
    def _start():
        print "start thread"
        for thread in threadLst:
            thread.start()
    cli.append(('start',_start," => initiate heartbeat if not already"))
    def _stop():
        print "stop thread"
        for thread in threadLst:
            thread.stop()
    cli.append(('stop',_stop," => stop heartbeat"))
    def _tryhelp():
        print('try help')
    cli.append((True,_tryhelp,""))
    cli.append(('','','exit => to shutdown'))
    #the main loop
    command = raw_input("]]] ")
    while command != 'exit':
        for condition, functor,doc in cli:
            if isinstance(condition,str):
                predicate = lambda a : re.compile(condition).match(command)
            if isinstance(condition,bool):
                predicate = lambda a : condition
            if callable(condition):
                predicate = condition
            if predicate(command):
                functor()
                break
        command = raw_input("]]] ")
    print 'bye'

"""MAIN
"""
if __name__ == '__main__':
    import sys

    def doNothing(nothing=None):
        return

    functorLst = [
            ('hello',lambda a : 'hello'),
            ('nothing',doNothing)
    ]

    server = HtmlRestServer(functorLst)
    heartbeat = Thread(doNothing)
    admin([heartbeat])
