/**
 * @overview Life of German Reallife - Gui Playerlist playerlist.js
 * @author VegaZ. Siga.
 * @copyright (c) 2008 - 2018 Life of German
 */

export default function playerList(globalData: IGlobalData): void {
    var playerlistBrowser: BrowserMp = null;
    var pList = [];
    var loaded = false;
    var factionPlayersMap: Map<number, number> = new Map<number, number>();
    const factionIds = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

    mp.events.add("loadPlayerListCEF", () => {
        if (playerlistBrowser !== null) {
            playerlistBrowser.destroy();
        }
        playerlistBrowser = mp.browsers.new('package://assets/html/onlinelist/index.html');
    });

    mp.events.add("showPlayerlist", (playersJson) => {
        if (!globalData.InMenu && !loaded) {
            globalData.InMenu = true;
            loaded = true;
            mp.gui.chat.activate(false);
            mp.gui.cursor.show(true, true);
            pList = JSON.parse(playersJson);
            playerlistBrowser.execute(`showPlayerList()`);
        } else if (loaded) {
            globalData.InMenu = false;
            loaded = false;
            mp.gui.cursor.show(false, false);
            mp.gui.chat.activate(true);
            playerlistBrowser.execute(`closePlayerList()`);
        }
    });

    mp.events.add("CEF:PlayerList_Loaded", () => {
        playerlistBrowser.execute(`clear_row()`);

        factionIds.forEach(f => {
            factionPlayersMap.set(f, 0);
        });

        pList.forEach((player) => {
            playerlistBrowser.execute(`addPlayerEntry('${player.Id}', '${player.Name}', '${player.FactionId}', '${player.Ping}');`);
            factionPlayersMap.set(player.factionId, factionPlayersMap.get(player.factionId) + 1);
        });

        factionPlayersMap.forEach((value, key) => {
            playerlistBrowser.execute(`setPlayerCount(${key}, ${value});`)
        });

        playerlistBrowser.execute(`setPlayerCount(-1, ${pList.length});`);
    });
}

//function getTable() {
//    var table = "";
//    pList.forEach((player) => {
//        var tableRow = "<tr><td>" + player.Id + "</td><td>" + player.Name + "</td><td>" + player.Ping + "</td>";
//        table = table + tableRow;
//    })
//    return document.write(table);
//}