# coding: utf-8


import tornado.websocket
import tornado.ioloop
from lib.monitor import *
import sys
import json

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


class RealTimeMonitorHandler(tornado.websocket.WebSocketHandler):

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

    def check_origin(self, origin):
        return True
        # 定义一个连接池，所有客户端的一个集合

    waiters = set()  # 集合元素不重复的对象

    # 1.建立连接
    def on_open(self, request):
        try:
            self.waiters.add(self)
        except Exception as e:
            print(e)
        pass

    # 2.发送消息
    def on_message(self, message):
        try:
            monitor = Monitor()
            data = dict()
            if message == "system":
                data = dict(
                    mem=monitor.mem(),
                    cpu=monitor.cpu(),
                    disk=monitor.disk(),
                    net=monitor.net(),
                    average_load=monitor.average_load(),
                )

            # 对消息进行处理，把新的消息推送到所有连接的客户端
            self.write_message(json.dumps(data))  # 广播
        except Exception as e:
            print(e)

    # 3.关闭连接
    def on_close(self):
        try:
            self.waiters.remove(self)
        except Exception as e:
            pass
        print "close"
