"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const msg_1 = __importDefault(require("../../models/msg"));
const msg_2 = require("../../../shared/types/msg");
const chan_1 = require("../../../shared/types/chan");
exports.default = (function (irc, network) {
    const client = this;
    irc.on("away", (data) => handleAway(msg_2.MessageType.AWAY, data));
    irc.on("back", (data) => handleAway(msg_2.MessageType.BACK, data));
    function handleAway(type, data) {
        const away = data.message;
        if (data.self) {
            const msg = new msg_1.default({
                self: true,
                type: type,
                text: away,
                time: data.time,
            });
            network.getLobby().pushMessage(client, msg, true);
            return;
        }
        network.channels.forEach((chan) => {
            let user;
            switch (chan.type) {
                case chan_1.ChanType.QUERY: {
                    if (data.nick.toLowerCase() !== chan.name.toLowerCase()) {
                        return;
                    }
                    if (chan.userAway === away) {
                        return;
                    }
                    // Store current away message on channel model,
                    // because query windows have no users
                    chan.userAway = away;
                    user = chan.getUser(data.nick);
                    const msg = new msg_1.default({
                        type: type,
                        text: away || "",
                        time: data.time,
                        from: user,
                    });
                    chan.pushMessage(client, msg);
                    break;
                }
                case chan_1.ChanType.CHANNEL: {
                    user = chan.findUser(data.nick);
                    if (!user || user.away === away) {
                        return;
                    }
                    user.away = away;
                    break;
                }
            }
        });
    }
});
