
var
    /**
     * @type {SlackWrapper}
    **/
    SLACK

    /**
     * @type {Array.<SlackChan|SlackGroup|SlackIms>}
    **/
    ,HIGHLIGHTED_CHANS = [];

;

/**
 * @constructor
**/
function SlackWrapper() {
    /** @type {number} */
    this.lastServerVersion = 0;

    /** @type {SlackData} */
    this.context = new SlackData(null);

    /** @type {!Object.<string, SlackHistory>} **/
    this.history = {};
}

SlackWrapper.prototype.update = function(data) {
    var now = Date.now();
    if (data["v"])
        this.lastServerVersion = data["v"];
    if (data["static"]) {
        this.context.updateStatic(data["static"], Date.now());
    }
    this.context.forEachChans(function(i) {
        if (i.lastMsg === i.lastRead) {
            var pos = HIGHLIGHTED_CHANS.indexOf(i);
            if (pos !== -1)
                HIGHLIGHTED_CHANS.splice(pos, 1);
        }
    });
    if (data["live"]) {
        for (var i in data["live"]) {
            var history = this.history[i];
            if (!history)
                history = this.history[i] = new SlackHistory(i, 250, data["live"][i], now);
            else
                history.pushAll(data["live"][i], now);
        }
        for (var roomId in data["live"]) {
            var chan = this.context.getChannel(roomId);
            if (chan) {
                if (this.history[roomId].messages.length)
                    chan.lastMsg = Math.max(chan.lastMsg, this.history[roomId].lastMessage().ts);
                if (!chan.archived) {
                    onMsgReceived(chan, data["live"][roomId]);
                    if (SELECTED_ROOM && data["live"][SELECTED_ROOM.id])
                        onRoomUpdated();
                }
            } else {
                outOfSync();
            }
        }
    }
    if (data["static"]) {
        onContextUpdated();
        if (data["static"]["typing"])
            onTypingUpdated();
    }
};

setInterval(function() {
    if (SLACK.context.cleanTyping(Date.now()))
        onTypingUpdated();
}, 1000);

/**
 * @param {string} text
 * @return {boolean}
**/
function isHighlighted(text) {
    var highlights = SLACK.context.self.prefs.highlights;
    for (var i =0, nbHighlights = highlights.length; i < nbHighlights; i++)
        if (text.indexOf(highlights[i]) !== -1) {
            return true;
        }
    return false;
}

/**
 * @param {SlackChan|SlackGroup|SlackIms} chan
 * @param {Array.<*>} msg
**/
function onMsgReceived(chan, msg) {
    if (chan !== SELECTED_ROOM || !window.hasFocus) {
        var selfReg = new RegExp("<@" +SLACK.context.self.id)
            ,highligted = false
            ,areNew = false
            ,newHighlited = false;
        msg.forEach(function(i) {
            if (parseFloat(i["ts"]) <= chan.lastRead) {
                return;
            }
            areNew = true;
            if (chan instanceof SlackIms || i.text.match(selfReg) || isHighlighted(i.text)) {
                if (HIGHLIGHTED_CHANS.indexOf(chan) === -1) {
                    newHighlited = true;
                    HIGHLIGHTED_CHANS.push(chan);
                }
                highligted = true;
            }
        });
        if (areNew) {
            updateTitle();
            var dom = document.getElementById(chan.id);
            if (dom) {
                dom.classList.add(R.klass.unread);
                if (highligted)
                    dom.classList.add(R.klass.unreadHi);
            }
            if (newHighlited && !window.hasFocus) {
                // TODO setting
                spawnNotification();
            }
        }
    }
}

/**
 * @param {SlackChan|SlackGroup|SlackIms} room
**/
function markRoomAsRead(room) {
    var highlightIndex = HIGHLIGHTED_CHANS.indexOf(room);
    if (room.lastMsg > room.lastRead) {
        sendReadMArker(room, room.lastMsg);
        room.lastRead = room.lastMsg;
    }
    if (highlightIndex >= 0) {
        HIGHLIGHTED_CHANS.splice(highlightIndex, 1);
        updateTitle();
    }
    var roomLi = document.getElementById(room.id);
    roomLi.classList.remove(R.klass.unread);
    roomLi.classList.remove(R.klass.unreadHi);
}

SLACK = new SlackWrapper();

