from tornado.ioloop import IOLoop
from tornado.options import define, options
from tornado.web import Application
from tornado.websocket import WebSocketHandler


define('debug', default=False, help='debug mode')
define('host', default='localhost', help='server host')
define('port', default=8888, help='server port')
define('secret', default='secret', help='secret key')


class OwltailWebsocketApp(Application):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.websockets = []


class WebSocket(WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        self.application.websockets.append(self)

    def on_close(self):
        self.application.websockets.remove(self)

    def on_message(self, message):
        for ws in self.application.websockets:
            if ws == self:
                continue
            ws.write_message(message)


if __name__ == '__main__':
    app = OwltailWebsocketApp(
        handlers=[(r"/websocket", WebSocket)],
        debug=options.debug,
        cookie_secret=options.secret,
    )
    app.listen(options.port)
    IOLoop.current().start()
