from abc import ABC

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

import sqlite3 as lite
import sys

import gfk_plate

import logging

from ini_logger import *

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

inputs = [
    {'type': "Materials", 'value':
        [{
            "e11": 42.5,
            "e22": 11,
            "e33": 11,
            "pr12": 0.28,
            "pr13": 0.28,
            "pr23": 0.28,
            "dens": 1950E-6,
            "g12": 4.2,
            "g13": 4.2,
            "g23": 2.56,
            "alp11": 5.7E-6,
            "alp22": 45E-6,
            "alp33": 45E-6,
            "k11": 0.72E3,
            "k22": 0.5E3,
            "k33": 0.5E3,
            "bet11": 0E-3,
            "bet22": 4E-3,
            "bet33": 4E-3,
            "d11": 4.4E3,
            "d22": 3.1E3,
            "d33": 3.1E3
        }]},
    {'type': "Angles", 'value': [90, 0, 0, 0, 0, 0]}
]

outputs = [
    {'type': "Srmax", 'value': 0},
    {'type': "Stmax", 'value': 2},
    {'type': "S1max", 'value': 4},
    {'type': "S2max", 'value': 4}
]


def update():
    outputs[0]['value'], outputs[1]['value'], outputs[2]['value'], outputs[3]['value'] = \
        gfk_plate.sim_rotor(inputs[0]['value'], inputs[1]['value'])


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()
