/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

var playerProfile = [];

var messages = null;

function loadHomePage(callback) {
    callAPI("getprofile", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password")
    }, function (data) {
        playerProfile = data.profile;
        setupProfile();
        initChat();
        refreshChat();
        setInterval(refreshChat, 1000 * 15);
        // Refresh health bar
        setInterval(function () {
            callAPI("getprofile", {
                username: localStorage.getItem("username"),
                password: localStorage.getItem("password")
            }, function (data) {
                playerProfile = data.profile;
                setupProfile();
            });
        }, 1000 * 30);
        callback();
    });
}

function setupProfile() {
    $(".username-healthbar").addClass("color-theme-" + SETTINGS["teams"][playerProfile.teamid]["color"]);
    $("#place-popup .action-button").addClass("color-theme-" + SETTINGS["teams"][playerProfile.teamid]["color"]);
    $("#player-level-badge").addClass("text-color-" + SETTINGS["teams"][playerProfile.teamid]["textcolor"]);

    $(".player-nickname").text(playerProfile.name);
    $("#player-level-badge").html("<i class=\"" + SETTINGS["teams"][playerProfile.teamid]["icon"] + "\"></i> &nbsp; Lv. " + playerProfile.level * 1);
    $("#playerinfo .usericon").html(getAvatarIcon(playerProfile.id, playerProfile.teamid));
    $("#playerinfo").on("click", ".usericon,.player-nickname", function () {
        router.navigate("/profile/" + playerProfile.id + "/" + playerProfile.name);
    });
    app.progressbar.set($("#player-healthbar"), (playerProfile.energy / playerProfile.maxenergy) * 100, 500);
}

function scanCode() {
    if (platform_type != "cordova") {
        app.dialog.alert("You can't scan barcodes with this device.", "Sorry!");
    }
    cordova.plugins.barcodeScanner.scan(
            function (result) {
                if (!result.cancelled) {
                    callAPI("code", {
                        username: localStorage.getItem("username"),
                        password: localStorage.getItem("password"),
                        code: result.text
                    }, function (resp) {
                        if (resp.item == "" && resp.munzee == "") {
                            app.dialog.alert("You didn't find anything new.", "");
                        } else {
                            if (resp.item == "") {
                                $("#founditem-block").addClass("display-none");
                            } else {
                                $("#founditem-name").text(resp.item);
                                $("#founditem-block").removeClass("display-none");
                            }
                            if (resp.munzee == "") {
                                $("#foundmunzee-block").addClass("display-none");
                            } else {
                                $("#foundmunzee-name").text(resp.munzee);
                                $("#foundmunzee-block").removeClass("display-none");
                            }
                            app.popup.open("#founditem-popup");
                        }
                    }, function (msg) {
                        app.dialog.alert(msg, "Error");
                    });
                }
            },
            function (error) {
                app.dialog.alert(error, "Scan Error");
            },
            {
                showTorchButton: true,
                prompt: "Find a code",
                resultDisplayDuration: 0,
                disableSuccessBeep: true
            }
    );
}

function openPlace(id, name) {
    var placepopupnonce = Math.random();
    $("#place-info").addClass("display-none");
    $("#place-error-msg").addClass("display-none");
    $("#place-popup .preloader").removeClass("display-none");
    $("#place-popup").data("placeid", id);
    $("#place-popup").data("placepopupnonce", placepopupnonce);
    $("#place-title").text(name);
    app.popup.open("#place-popup");

    updatePlaceStats(id, function (success) {
        $("#place-popup .preloader").addClass("display-none");
        $("#place-info").removeClass("display-none");
    }, function (error) {
        $("#place-error-msg").text(error);
        $("#place-popup .preloader").addClass("display-none");
        $("#place-error-msg").removeClass("display-none");
    });

    var refreshPlaceStats = function () {
        if (id != $("#place-popup").data("placeid")) {
            console.log("refreshPlaceStats: place ID changed, stopping refresh");
            return;
        }
        if (placepopupnonce != $("#place-popup").data("placepopupnonce")) {
            console.log("refreshPlaceStats: placepopupnonce changed, stopping redundant refresh");
            return;
        }
        if (app.popup.get("#place-popup").opened) {
            updatePlaceStats(id);
            setTimeout(refreshPlaceStats, 2000);
        }
    };

    setTimeout(refreshPlaceStats, 2000);
}

function updatePlaceStats(id, successCallback, errorCallback) {
    callAPI("getplace", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password"),
        id: id
    }, function (resp) {
        var place = resp.place;
        if (place.teamid != null && place.teamid > 0) {
            $("#place-info").removeClass();
            $("#place-info").addClass("color-theme-" + SETTINGS["teams"][place.teamid]["color"]);
            $("#place-image").attr("src", "img/place/" + SETTINGS["teams"][place.teamid]["color"] + ".png");
            if (playerProfile.teamid == place.teamid) {
                $("#magic-action-label").text("Defend");
            } else {
                $("#magic-action-label").text("Attack");
            }

            $("#place-artifact-list").html("");
            place.artifacts.forEach(function (artifact) {
                $("#place-artifact-list").append("<span id=\"artifact-icon-" + artifact.id + "\" data-artifact=\"" + artifact.id + "\" data-energy=\"" + artifact.energy + "\" data-maxenergy=\"" + artifact.maxenergy + "\" class=\"place-artifact-icon " + artifact.icon + " fa-2x margin-right text-color-" + artifact.color + "\"></span>");
            });
        } else {
            $("#place-info").addClass("color-white");
            $("#place-image").attr("src", "img/place/white.png");
            $("#magic-action-label").text("Control");
        }

        if (place.currentlife != null && place.maxlife != null) {
            app.progressbar.set("#place-health-bar", (place.currentlife / place.maxlife) * 100, 100);
        } else {
            app.progressbar.set("#place-health-bar", 100, 100);
        }

        if (typeof successCallback == "function") {
            successCallback();
        }
    }, function (error) {
        if (typeof errorCallback == "function") {
            errorCallback(error);
        }
    });
}

$("#magic-action-button").click(function () {
    callAPI("placeact", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password"),
        id: $("#place-popup").data("placeid")
    }, function (resp) {
        updatePlaceStats($("#place-popup").data("placeid"));
        app.toast.show({
            text: '<i class="fas fa-check"></i> ' + resp.msg,
            position: "bottom",
            destroyOnClose: true,
            closeTimeout: 1000 * 2
        });
    }, function (error) {
        app.toast.show({
            text: '<i class="fas fa-question"></i> ' + error,
            position: "bottom",
            destroyOnClose: true,
            closeTimeout: 1000 * 2
        });
    });
});