#!/usr/bin/env python
# -*- coding: utf_8 -*-

import sys
import os
import signal
import json
from tornado.wsgi import WSGIContainer
from tornado.web import Application, RequestHandler, FallbackHandler
from tornado.ioloop import IOLoop
from tornado.autoreload import watch
from view import app
from view.monitor import DeviceMessageHandler, NotifyHandler, WatchHandler
from app import config

class GracefulExit(SystemExit):
    code = 1

class VueHandler(RequestHandler):
    def get(self):
        self.write(json.dumps({ 'code': 200, 'msg': 'success', 'data': self.request.remote_ip }))

def raise_graceful_exit(*args):
    IOLoop.current().stop()
    print("Gracefully shutdown", args)
    raise GracefulExit()

def start():
    settings = {
        'debug': config['DEBUG'],
    #     'template_path': config['TEMPLATE_PATH'],
    #     'static_path': config['STATIC_PATH'],
        'static_url_path': '',
    }
    watch(os.sep.join([os.getcwd(), "restart.json"]))
    wsgi_app = WSGIContainer(app)
    application = Application([
        (r'/', VueHandler),
        (r"/api/v1/evm_store/monitor", DeviceMessageHandler),
        (r"/api/v1/evm_store/watch", WatchHandler),
        (r"/ws/v1/notify", NotifyHandler),
        (r'.*', FallbackHandler, dict(fallback=wsgi_app))
    ], **settings)

    if len(sys.argv) == 2:
        port = int(sys.argv[1])
        application.listen(port, address=config['HOST'], xheaders=True)
    else:
        port = config['PORT']
        application.listen(port, address=config['HOST'], xheaders=True)

    print(config['LOGO'])
    print("server running at %s:%d" % (config['HOST'], port))

    # 主进程退出信号
    signal.signal(signal.SIGINT, raise_graceful_exit)
    signal.signal(signal.SIGTERM, raise_graceful_exit)

    # instance = tornado.ioloop.IOLoop.instance()
    # tornado.autoreload.start(instance)
    # instance.start()
    IOLoop.instance().start()

if __name__ == '__main__':
    start()