Ext.define("IceCap.util.Watchdog", {

    singleton: true,

    config: {
        socket: null
    },

    constructor: function (o_config) {

        var i_self = this;
        i_self.initConfig(o_config);

        var i_location = window.location;
        try {

            var s_protocol = location.protocol;

            var s_path = "ws://";

            if (s_protocol.indexOf("https") > -1) {
                s_path = "wss://";
            }

            var i_websocket = new WebSocket(s_path + i_location.host + "/icecap/watchdog/ping");

            i_self.setSocket(i_websocket);

            i_websocket.onmessage = function (i_event) {
                i_self.onMessage(i_event.data);
            };

            i_websocket.onopen = function (i_event) {
                i_self.onOpen(i_event);
            };

            var i_window = Ext.getWin();

            i_window.on({
                close: function () {
                    i_websocket.close();
                }
            });
        }
        catch(err) {
            console.log(err);
        }

    },

    onMessage: function(o_data) {

        var i_self = this;

        Ext.defer(i_self.ping, 5000, i_self);
    },

    onOpen: function () {

        var i_self = this;
        Ext.defer(i_self.ping, 5000, i_self);
    },

    ping: function() {

        var i_self = this;

        var i_websocket = i_self.getSocket();

        var i_provider = IceCap.util.Handler.getProvider();

        var a_terminals = Ext.Array.from(i_provider.get("activeterminals"));
        var a_sessions = IceCap.util.Handler.getSessions();

        i_websocket.send(JSON.stringify({
            "activeTerminals": a_terminals,
            "sessions": a_sessions
        }));
    },
})
