const Message = require('./message.js').Message
    ,MeMessage = require('./message.js').MeMessage
    ,NoticeMessage = require('./message.js').NoticeMessage
    ,RoomHistory = require('./message.js').RoomHistory;

/**
 * @constructor
 * @extends {RoomHistory}
 * @param {string} serviceId
 * @param {Room|string} room or roomId
 * @param {string} idPrefix
 * @param {number} keepMessages number of messages to keep in memory
 * @param {Array=} evts
 * @param {number=} now
**/
function SlackHistory(remoteId, room, idPrefix, keepMessages, evts, now) {
    RoomHistory.call(this, room, keepMessages, evts, now);

    /** @const @type {string} */
    this.remoteId = remoteId;

    /** @const @type {string} */
    this.idPrefix = idPrefix;
}
SlackHistory.prototype = Object.create(RoomHistory.prototype);
SlackHistory.prototype.constructor = SlackHistory;

SlackHistory.prototype.messageFactory = function(ev, ts) {
    if (!ev["user"])
        ev["user"] = ev["bot_id"];
    ev["user"] = this.idPrefix +ev["user"];
    if (ev["reactions"]) {
        ev["reactions"].forEach((r) => {
            for (var i =0, nbUsers =r["users"].length; i < nbUsers; i++)
                r["users"][i] = this.idPrefix +r["users"][i];
        });
    }
    if (ev["is_ephemeral"] === true)
        return new NoticeMessage(ev, ts);
    if (ev["subtype"] === "me_message")
        return new MeMessage(ev, ts);
    return new Message(ev, ts);
};

/**
 * @return {number} ts
**/
SlackHistory.prototype.push = function(ev, t) {
    var msg;
    if (!ev["type"] || ev["type"] === "message") {
        var exists = false
            ,targetId = ev["ts"]
            ,modifArg = ev;

        if (ev["subtype"] === "message_changed") {
            if (ev["previous_message"])
                targetId = ev["previous_message"]["ts"];
            else if (ev["message"])
                targetId = ev["message"]["ts"];
            modifArg = ev["message"]
        } else if (ev["subtype"] === "message_deleted" && (ev["previous_message"] || ev["deleted_ts"])) {
            if (ev["previous_message"])
                targetId = ev["previous_message"]["ts"];
            else
                targetId = ev["deleted_ts"];
            modifArg = null;
        }
        if (modifArg) {
            if (modifArg["edited"])
                modifArg["edited"] = Math.round(parseFloat(modifArg["edited"]["ts"]) * 1000);
            if (modifArg["ts"])
                modifArg["ts"] = parseFloat(modifArg["ts"]) * 1000;
            if (!modifArg["id"])
                modifArg["id"] = targetId;
            if (modifArg["attachments"] && modifArg["attachments"].length)
                modifArg["attachments"].forEach((a) => {
                    a.ts *= 1000;
                });
        }
        for (var i =0, nbMsg = this.messages.length; i < nbMsg; i++) {
            msg = this.messages[i];
            if (msg.id === targetId) {
                msg.update(modifArg, t);
                exists = true;
                break;
            }
        }
        if (!exists) {
            msg = this.messageFactory(ev, t);
            this.messages.push(msg);
        }
    } else if (ev["type"] === "reaction_added") {
        msg = this.addReaction(ev["reaction"], this.idPrefix +ev["user"], ev["item"]["ts"], t);
    } else if (ev["type"] === "reaction_removed") {
        msg = this.removeReaction(ev["reaction"], this.idPrefix +ev["user"], ev["item"]["ts"], t);
    } else {
        return 0;
    }
    while (this.messages.length > this.keepMessages)
        this.messages.shift();
    return msg ? msg.ts : 0;
};

SlackHistory.prototype.resort = function() {
    this.messages.sort(function(a, b) {
        return a.ts -b.ts;
    });
};

module.exports.SlackHistory = SlackHistory;

