##############################################################################
#

# Note: This is a Python 2 http webclip server.

import SimpleHTTPServer
import SocketServer
#import io
import time

from urlparse import urlparse
import json

PORT = 9176
REPLYMAX = 30

def now ():
    return int(time.time())
    
db = [
  {
    'name':'test',
    'created':now(),
    'data':'Hello World'
  }
]

class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def do_GET(self):
        # Create an in-memory output file for the new workbook.
        body = "["
        sep = ''
        origin = self.headers.get('HTTP_ORIGIN','*')
        url = urlparse(self.path)
        
        params = url[4].split('&')  # query
        if url[4] == '':
          return;
          
        time = 0
        group = None
        print(params)
        for param in params:
          tokens = param.split('=')        
          if len(tokens) > 0 and tokens[0] == 'time':
            time = int(tokens[1])
          if len(tokens) > 0 and tokens[0] == 'group':
            group = tokens[1]

        if group == None:
          return;
          
        if time > 0:
          time = now()-time
        index = 0
        for entry in db:
          if index > REPLYMAX:
            continue
          if group != None and (not("group" in entry) or entry["group"]!=group):
            continue
          if time == 0 or (time > 0 and entry["created"]>time):
            body = body + sep
            body = body + json.dumps(entry)
            sep = ','
          index = index + 1
          
        # Construct a server response.
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin' , origin)
        self.send_header('Access-Control-Allow-Credentials', 'true')   
        self.end_headers()

        body = body + ']'
        self.wfile.write(body)

        return

    def do_POST(self):
        origin = self.headers.get('HTTP_ORIGIN','*')
       # Doesn't do anything with posted data
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        body = self.rfile.read(content_length) # <--- Gets the data itself
        paste = json.loads(body)
        paste["created"]=now()
        db.insert(0,paste)
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin' , origin)
        self.send_header('Access-Control-Allow-Credentials', 'true')   
        self.end_headers()
        self.wfile.write("OK")


print('Server listening on port '+str(PORT)+' ..')
httpd = SocketServer.TCPServer(('', PORT), Handler)
httpd.serve_forever()
