#!/usr/bin/env python
# -*- coding: utf_8 -*-
import sys
import os
import signal
from fullstack.log import logger
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, NotifyHandler, ThreadNotifyHandler
from datetime import datetime
from app import config, signalManager

def terminal_application(a, b):
    IOLoop.instance().stop()
    print("Good Bye!!!")

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, terminal_application)
 
    # # 主进程退出信号
    # signal.signal(signal.SIGINT, terminal_application)
    # signal.signal(signal.SIGTERM, terminal_application)

    IOLoop.instance().start()

if __name__ == '__main__':
    start()