#!/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, NotifyHandler, ThreadNotifyHandler
from app import config, signalManager

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

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'/ws/api/v1/notify', NotifyHandler),
        (r'/ws/api/v1/threadnotify', ThreadNotifyHandler),
        (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))

    # if sys.platform == "linux":
    #     # 子进程退出后向父进程发送的信号
    #     signal.signal(signal.SIGCHLD, IOLoop.instance().stop)
 
    # # 主进程退出信号
    # signal.signal(signal.SIGINT, IOLoop.instance().stop)
    # signal.signal(signal.SIGTERM, IOLoop.instance().stop)

    IOLoop.instance().start()

if __name__ == '__main__':
    start()