from abc import ABC

import tornado.ioloop
import tornado.web
import tornado.escape
import collections
import json

import sqlite3 as lite
import sys

import logging

from ini_logger import *

#log_dir = r'/var/log/server'
#ini_logger(log_dir)

inputs = [
    {'type': "INPUT", 'value': [0]},
    {'type': "INPUT", 'value': [1]},
    {'type': "INPUT", 'value': [2]},
    {'type': "INPUT", 'value': [3]},
    {'type': "INPUT", 'value': [4]}
]

outputs = [
    {'type': "OUTPUT", 'value': [0]},
    {'type': "OUTPUT", 'value': [2]},
    {'type': "OUTPUT", 'value': [4]}
]

def update():
    do_something = 1


class MainHandler(tornado.web.RequestHandler, ABC):
    def prepare(self):
        self.set_header("Content-Type", "application/json")
        if self.request.headers.get('Content-Type') == 'application/json':
            print(self.request.body)
            self.json_args = json.loads(self.request.body.decode('utf-8'))
        else:
            self.json_args = None

    def get(self, param):
        print("INFO: GET /" + param)
        if param == "inputs":
            self.write(json.dumps(inputs))
        elif param == "outputs":
            self.write(json.dumps(outputs))
        elif param == "status":
            self.write("{\"status\": \"ready\"}")
        elif param == "stop":
            instance = tornado.ioloop.IOLoop.instance()
            instance.add_callback(instance.stop)
        else:
            self.write("Error: GET /" + param)
            print("Error: GET /" + param)

    def post(self, param):
        if param == "update":
            if self.json_args is not None:
                print("INFO: GET /" + param + "with body: " + self.json_args.dump())
                counter = 0
                for entity in self.json_args:
                    inputs[counter]['value'] = entity['value']
                    counter = counter + 1
            update()
            self.write(json.dumps(outputs))
        else:
            self.write("Error: POST /" + param)
            print("Error: POST /" + param)


def make_app():
    return tornado.web.Application([
        (r"/(.*)", MainHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(int(sys.argv[1]))
    tornado.ioloop.IOLoop.current().start()
