'''
Author: your name
Date: 2021-04-14 14:12:18
LastEditTime: 2021-06-29 20:22:42
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\start.py
'''
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import sys
import os
import signal
from datetime import datetime
from tornado.wsgi import WSGIContainer
from tornado.web import Application, RequestHandler, FallbackHandler
from tornado.ioloop import IOLoop
from tornado.autoreload import watch
from fullstack.log import logger
from view import app
from view.monitor import DeviceMessageHandler, NotifyHandler
from app import config

class GracefulExit(SystemExit):
    code = 1

class VueHandler(RequestHandler):
    def get(self):
        remote_ip = self.request.remote_ip
        logger.info("remote_ip %s" % remote_ip)
        self.render("index.html")

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'/index', VueHandler),
        (r"/api/v1/evm_store/monitor", DeviceMessageHandler),
        (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'])
    else:
        port = config['PORT']
        application.listen(port, address=config['HOST'])

    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)

    IOLoop.instance().start()

if __name__ == '__main__':
    start()