# coding: utf-8

import tornado.httpserver
import tornado.web
import tornado.websocket
import tornado.ioloop
import tornado.gen
import tornadoredis
import sys
from decouple import config


reload(sys)
sys.setdefaultencoding('utf-8')


class BuildSiteMsgHandler(tornado.websocket.WebSocketHandler):

    def __init__(self, *args, **kwargs):
        super(BuildSiteMsgHandler, self).__init__(*args, **kwargs)
        self.listen()

    def check_origin(self, origin):
        return True

    def open(self, *args, **kwargs):
        pass

    @tornado.gen.engine
    def listen(self):
        port = config('CLIENT_REDIS_PORT', cast=int)
        self.client = tornadoredis.Client(host='localhost', port=port)
        self.client.connect()
        yield tornado.gen.Task(self.client.subscribe, 'build_site')
        self.client.listen(self.send_new_msg)

    def on_message(self, msg):

        pass

    def on_close(self):
        if self.client.subscribed:
            self.client.unsubscribe('build_site')
            self.client.disconnect()

    def send_new_msg(self, msg):
        if msg.kind == 'message':
            self.write_message(str(msg.body))
        if msg.kind == 'disconnect':
            self.close()
