'''
Author: your name
Date: 2021-06-15 17:40:09
LastEditTime: 2021-07-22 12:56:09
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\resources\manager.py
'''
# -*- coding: utf-8 -*-
import signal
from tornado.wsgi import WSGIContainer
from tornado.web import Application, FallbackHandler
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from flask_script import Manager
from flask_migrate import Migrate
from application.app import create_app, db
from application.config import config
from views.monitor import DeviceMessageHandler, NotifyHandler, WatchHandler

# 根据配置初始化app
app = create_app(config)
migrate = Migrate(app, db)
manager = Manager(app)

class GracefulExit(SystemExit):
    code = 1

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


@manager.command
def run():
    """
    生产模式启动命令函数
    To use: python3 manager.py run
    """
    # app.logger.setLevel(app.config.get('LOG_LEVEL', logging.INFO))

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(3000, address='127.0.0.1')
    IOLoop.instance().start()

@manager.command
def debug():
    """
    debug模式启动命令函数
    To use: python3 manager.py debug
    """
    # app.logger.setLevel(logging.DEBUG)
    # app.run(debug=True, port=3000, host='127.0.0.1')
    wsgi_app = WSGIContainer(app)
    application = Application([
        (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))
    ], **{ 'debug': True, })
    application.listen(3001, address='127.0.0.1', xheaders=True)

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

    IOLoop.instance().start()

if __name__ == '__main__':
    manager.run()
