/**
 * @overview Life of German Reallife - Faction Manager Main (main.js)
 * @author hydrant
 * @copyright (c) 2008 - 2018 Life of German
 */

export default function factionManagement() {

    var manageFactionRanksBrowser = null;
    var rankData = null;

    mp.events.add('manageFactionRanks', (ranks) => {
        if (manageFactionRanksBrowser !== null) return;
        manageFactionRanksBrowser = mp.browsers.new('package://assets/html/factionmanagement/ranks/index.html');

        mp.gui.chat.activate(false);
        rankData = JSON.parse(ranks);
    });

    mp.events.add('onManageFactionRanksLoaded', () => {
        if (manageFactionRanksBrowser !== null) {

            manageFactionRanksBrowser.execute(`loadData(` + JSON.stringify(rankData.Ranks) + `)`);
            mp.gui.cursor.show(true, true);
        }
    });

    mp.events.add('saveFactionRankData', function (data) {
        if (manageFactionRanksBrowser !== null) {
            manageFactionRanksBrowser.destroy();
            mp.gui.cursor.show(false, false);
            mp.gui.chat.activate(true);

            var obj: FactionRanks = {
                factionId: rankData.FactionId,
                ranks: JSON.parse(data)
            };

            mp.events.callRemote('OnFactionRanksEdit', JSON.stringify(obj));

            manageFactionRanksBrowser = null;
        }
    });
}