/// <reference path="..\..\GSMyAdmin\WebRoot\Scripts\UI.js" />
/// <reference path="..\..\GSMyAdmin\WebRoot\Scripts\API.js" />

/* global API,UI,PluginHandler */
/*eslint eqeqeq: 0*/

this.plugin = {
    PreInit: function () {
        //Called prior to the plugins initialisation, before the tabs are loaded.
        //This method must not invoke any module/plugin specific API calls.
    },

    PostInit: function () {
        //The tabs have been loaded. You should wire up any event handlers here.
        UI.SetCustomConsoleMessageProcesssor(handleRconTables);

        setWizardCallback("mapChange", function () {
            //Finished function, handle the actual request to AMP to change map here
        }, function () {
            //Reset function - Grab all the data here and populate the WIZARD div
        });

        var button = $('<button/>', { class: "slideIcon icons_restart", "data-module": "srcdsModule", "data-method": "ShowMapChangeWizard", "data-showstates": "20,50" });
        button.append($('<span/>', { text: "Change Map" }));
        $("#statusButtonGroup").append(button);
    },

    AMPDataLoaded: function () {
        //Any data you might need has been loaded, you should wire up event handlers which use data such as settings here.
        var recordDemoButton = $("<button>", { text: "Record Demo", click: recordDemo, "data-showstates" : "20" });
        $("#tab_status .buttonGroup").append(recordDemoButton);
        var tournPw = $("<h1>", { text: "", style: "display:none", id: "tournPw", "data-showstates": "20" });
        $("#tab_status").append(tournPw);
    },

    SettingChanged: function (node, value) {
        switch (node) {
            case "srcdsModule.SRCDSSettings.ServerType":
                API.Core.GetSettingValues("srcdsModule.SRCDSSettings.Map", true, function (result) {
                    var mapCombo = $("select[data-settingnode='srcdsModule.SRCDSSettings.Map']");
                    mapCombo.empty();

                    var prevCategory = "misc";

                    Object.keys(result).forEach(function (key) {
                        var value = result[key];

                        var parts = value.split("_", 2);
                        if (parts.length === 2) {
                            var category = parts[0];
                            if (category != prevCategory) {
                                prevCategory = category;
                                mapCombo.append($("<option/>", { "data-noset": "true" }));
                                mapCombo.append($("<option/>", { value: key, text: "-- " + getCategoryName(category) + " --", "class": "mapCatName", "data-noset": "true" }));
                            }
                        }

                        mapCombo.append($("<option/>", { value: key, text: value }));
                    });
                });
                break;
            default:
                return;
        }
    },

    PushedMessage: function (source, message, parameters) {
        switch (message) {
            case "tournamentpassword":
                $("#tournPw").show();
                $("#tournPw").text("Tournament password: " + parameters);
        }
    },

    Reset: function () {

    }
};

this.tabs = [
    //{
    //    File: "MapCycle.html", //URL to fetch the tab contents from. Relative to the plugin WebRoot directory.
    //    ExternalTab: false,   //If True, 'File' is treated as an absolute URL to allow contents to be loaded from elsewhere.
    //    //Note that the appropriate CORS headers are required on the hosting server to allow this.
    //    ShortName: "MapCycle",    //Name used for the element. Prefixed with tab_PLUGINNAME_
    //    Name: "Map Cycle Editor",     //Display name for the tab.
    //    Light: true,                //Use the 'light' theme for this tab.
    //    Category: "Settings",
    //    Click: mapCycleOpen,
    //    Icon: "mapcycle.png",
    //}
];

this.stylesheet = "CSS/Stylesheet.css";    //Styles for tab-specific styles

function ShowMapChangeWizard() {
    //API.Core.GetSettingValues("srcdsModule.SRCDSSettings.Map", true, function (result) {
    //    var container = $("#ampMapEntry");
    //    container.empty();

    //    var resultKeys = Object.keys(result);

    //    var prevCategory = "misc";

    //    Object.keys(result).forEach(function (key) {
    //        var map = result[key];

    //        var parts = map.split("_", 2);
    //        if (parts.length === 2) {
    //            var category = parts[0];
    //            if (category != prevCategory) {
    //                container.append($("<h3/>", { text: getCategoryName(category) }));
    //                prevCategory = category;
    //            }
    //        }

    //        var mapEntry = $("<div/>", {
    //            "class": "ampMapEntry", "data-mapname": map
    //        });

    //        mapEntry.append($("<img/>", {
    //            src: "http://placehold.it/180x180"
    //        }));

    //        mapEntry.append($("<button/>", {
    //            text: "^", "data-mapname": map
    //        }).mouseup(function () {
    //            var map = $(this).data("mapname");
    //            console.log("up button pushed" + map);
    //        }));

    //        mapEntry.append($("<button/>", {
    //            text: "v", "data-mapname": map
    //        }).mouseup(function () {
    //            var map = $(this).data("mapname");
    //            console.log("down button pushed" + map);
    //        }));

    //        mapEntry.append($("<div/>", { "class": "mapName", text: map }));

    //        container.append(mapEntry);
    //    });
    //});
}

var categoryNames = {
    "ctf": "Capture the Flag",
    "dom": "Domination",
    "arena": "Arena",
    "cp": "Capture Point",
    "koth": "King of the Hill",
    "mvm": "Mann v.s. Machine",
    "pl": "Payload",
    "plr": "Payload Race",
    "sd": "Special Delivery",
    "rd": "Robot Destruction",
    "tc": "Territorial Control",
    "tr": "Training",
    "cs": "Hostage Rescue",
    "de": "Bomb Defusal",
    "as": "Assassination",
    "rp": "Roleplay",
    "gm": "Garry's Mod",
    "sb": "SpaceBuild",
    "gms": "Stranded",
    "zs": "Zombie Survival",
    "fw": "Fort Wars",
    "l4d": "Left 4 Dead (2)"
};

function getCategoryName(cat) {
    if (categoryNames[cat.toLowerCase()] != undefined) {
        return categoryNames[cat.toLowerCase()];
    }

    return cat;
}

async function recordDemo() {
    var result = await UI.PromptAsync("Demo Name", "Name for new demo file");
    if (result != null) {
        var recordResult = await API.srcdsModule.RecordDemoAsync(result);
        if (recordResult.Status == false) {
            UI.ShowModalAsync("Unable to record demo", recordResult.Reason, UI.Icons.Exclamation, UI.OKActionOnly);
        }
    }
}

function mapCycleOpen() { // This is called when the Map Cycle Tab gets opened

    //if (mapCycle == null) {
    //    API.srcdsModule.GetMapCycle(function (result) {
    //        mapCycle = result;
    //        buildMapCycle();
    //    });
    //}
    //else
    //{
    //    buildMapCycle();
    //}
    API.srcdsModule.GetMapCycle(function (result) {
        if (result != null)
        {
            buildMapCycle(result);
        }
    });
}

function buildMapCycle(data) {
    var container = $("#ampMapList");
    container.empty();

    Object.keys(data).forEach(function (key) {
        var map = data[key];

        var mapEntry = $("<div/>", {
            "class": "ampMapEntry", "data-mapname": map, "data-mapindex": key
        });

        mapEntry.append($("<img/>", {
            src: "http://placehold.it/180x180"
        }));

        mapEntry.append($("<button/>", {
            text: "^"
        }).mouseup(function () {
            var map = $(this).parent().data("mapname");
            var index = $(this).parent().data("mapindex");

            console.log("up button pushed" + map + "" + index);

            if (index != 0) { // First entry
                API.srcdsModule.MoveMapEntry(index, index - 1, mapCycleOpen);
                //mapCycle.splice(index - 1, 0, mapCycle.splice(index, 1)[0]);
                //buildMapCycle();
            }
        }));

        mapEntry.append($("<button/>", {
            text: "v"
        }).mouseup(function () {
            var map = $(this).parent().data("mapname");
            var index = $(this).parent().data("mapindex");

            console.log("down button pushed" + map + "" + index);

            if (index != data.length) { // Last entry

            API.srcdsModule.MoveMapEntry(index, index + 1, mapCycleOpen);

                //mapCycle.splice(index + 1, 0, mapCycle.splice(index, 1)[0]);
                //buildMapCycle();
            }
        }));

        mapEntry.append($("<button/>", {
            text: "x"
        }).mouseup(function () {
            var map = $(this).parent().data("mapname");
            var index = $(this).parent().data("mapindex");

            API.srcdsModule.RemoveMapEntry(index, mapCycleOpen);
            //mapCycle.splice(index, 1)
            //buildMapCycle();
        }));

        mapEntry.append($("<div/>", { "class": "mapName", text: map }));

        container.append(mapEntry);
    });
}

var tableLineReg = /^([\w\/]+?)\s*: (.+?)$/;
var tablePartSepReg = /\s+/;

function handleRconTables(element) {
    var text = element.text();
    var lines = text.split("\n");
    if (tableLineReg.test(lines[0]) === false || lines.length === 1) {
        return false;
    }

    element.text("");

    var newContents = $("<table/>", { "class": "TwoColLine" });
    newContents.append("<thead><tr><th>Key</th><th>Value</th></thead>");
    var newBody = $("<tbody/>");
    var infoTable = true;
    var inHashTable = false;

    var hashTable, hashBody, parts, p;

    for (var i = 0; i < lines.length; i++) {
        var line = lines[i];
        if (infoTable) {
            parts = line.match(tableLineReg);
            if (parts == null) {
                infoTable = false;
                newContents.append(newBody);
                element.append(newContents);

                if (line[0] !== "#") {
                    element.append($("<pre/>", { text: line }));
                    continue;
                }
            } else {
                var newRow = $("<tr/>");
                newRow.append($("<td/>", { text: parts[1] }));
                newRow.append($("<td/>", { text: parts[2] }));
                newBody.append(newRow);
            }
        }

        if (line[0] === "#") {
            line = line.slice(2);
            parts = line.split(tablePartSepReg);

            if (parts[0] === "") {
                parts = parts.splice(1);
            }

            if (inHashTable == false) {
                hashTable = $("<table/>");
                var hashHead = $("<thead/>");
                var hashRow = $("<tr/>");

                for (p = 0; p < parts.length; p++) {
                    hashRow.append($("<th/>", { text: parts[p] }));
                }

                hashHead.append(hashRow);
                hashTable.append(hashHead);
                hashBody = $("<tbody/>");
                hashTable.append(hashBody);

                inHashTable = true;
            }
            else {
                hashRow = $("<tr/>");

                for (p = 0; p < parts.length; p++) {
                    hashRow.append($("<td/>", { text: parts[p] }));
                }

                hashBody.append(hashRow);
            }
        }
        else if (infoTable == false) {
            if (inHashTable) {
                inHashTable = false;
                hashTable.append(hashBody);
                element.append(hashTable);
            }
            element.append($("<pre/>", { text: line }));
        }
    }

    return true;
}