"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("banlist", (list) => {
        const data = list.bans.map((ban) => ({
            hostmask: ban.banned,
            banned_by: ban.banned_by,
            banned_at: ban.banned_at * 1000,
        }));
        handleList(chan_1.SpecialChanType.BANLIST, "Ban list", list.channel, data);
    });
    irc.on("inviteList", (list) => {
        const data = list.invites.map((invite) => ({
            hostmask: invite.invited,
            invited_by: invite.invited_by,
            invited_at: invite.invited_at * 1000,
        }));
        handleList(chan_1.SpecialChanType.INVITELIST, "Invite list", list.channel, data);
    });
    function handleList(type, name, channel, data) {
        if (data.length === 0) {
            const msg = new msg_1.default({
                time: new Date(),
                type: msg_2.MessageType.ERROR,
                text: `${name} is empty`,
            });
            let chan = network.getChannel(channel);
            // Send error to lobby if we receive empty list for a channel we're not in
            if (typeof chan === "undefined") {
                msg.showInActive = true;
                chan = network.getLobby();
            }
            chan.pushMessage(client, msg, true);
            return;
        }
        const chanName = `${name} for ${channel}`;
        let chan = network.getChannel(chanName);
        if (typeof chan === "undefined") {
            chan = client.createChannel({
                type: chan_1.ChanType.SPECIAL,
                special: type,
                name: chanName,
                data: data,
            });
            client.emit("join", {
                network: network.uuid,
                chan: chan.getFilteredClone(true),
                shouldOpen: false,
                index: network.addChannel(chan),
            });
        }
        else {
            chan.data = data;
            client.emit("msg:special", {
                chan: chan.id,
                data: data,
            });
        }
    }
});
