/*
 * 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/.
 */


function checkAccountStatus(callback) {
    if (inStorage("accountnumber")) {
        apirequest(SETTINGS.apis.authorstartverify, {
            accountnumber: getStorage("accountnumber"),
            accountkey: (inStorage("accountkey") ? getStorage("accountkey") : "")
        }, function (resp) {
            if (resp.status == "OK") {
                if (resp.authok && resp.accountok) {
                    callback(true);
                } else if (!resp.authok && resp.accountok) {
                    // verify phone or email
                    // openAccountVerify(resp.verifymsg);
                    callback("noauth", resp.verifymsg);
                } else if (!resp.authok && !resp.accountok) {
                    callback(false);
                } else {
                    callback("badstate");
                }
            } else {
                router.back();
                // Server is saying something's wrong, let's clear the account number in case
                // the user wants to try a different one.
                removeFromStorage("accountnumber");
                app.dialog.alert(resp.msg, "Error");
                sendErrorReport("Account", "Couldn't check account status", resp.msg);
            }
        }, function (xhr, status, error) {
            router.back();
            app.dialog.alert("Something went wrong. Try again later.", "Error");
            sendErrorReport("Account", "Couldn't check account status", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
        });
    } else {
        callback(false);
    }
}

function checkIfAccountGoodWithPaymentMethod(successcb, errorcb) {
    if (!inStorage("accountnumber") || !inStorage("accountkey")) {
        successcb(false);
        return;
    }
    apirequest(SETTINGS.apis.getaccountinfo, {
        accountnumber: getStorage("accountnumber"),
        accountkey: getStorage("accountkey")
    }, function (success) {
        if (success.status == "OK") {
            if (success.payments_setup === false) {
                successcb(false);
            } else {
                successcb(true);
            }
        } else {
            errorcb(success.msg);
        }
    }, function (error) {
        errorcb("Couldn't get your account info. Try again later.");
    }, "GET");
}

function openAccountVerify(verifymsg) {
    app.dialog.prompt(verifymsg, "Verify Your Account", function (val) {
        verifyCode(val);
    }, function (cancel) {
        // shrug
    }, "");
}

/**
 * Confirm auth/login code with server and store login key if successful.
 * @param {type} code
 * @returns {undefined}
 */
function verifyCode(code) {
    app.dialog.preloader("Verifying...");
    apirequest(SETTINGS.apis.verifyauthcode, {
        code: code,
        accountnumber: getStorage("accountnumber")
    }, function (resp) {
        app.dialog.close();
        if (resp.status == "OK") {
            setStorage("accountkey", resp.authkey);
            app.dialog.alert("This device has been successfully linked to your Helena Express account.", "Account verified!");
            sendActionReport("Account", "Device linked OK");
            displayAccountInfo();
        } else if (resp.status == "ERROR") {
            app.dialog.alert(resp.msg, "Error");
            sendErrorReport("Account", "Device linking", resp.msg);
        }
    }, function (xhr, status, error) {
        app.dialog.close();
        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
        sendErrorReport("Account", "Couldn't verify account code", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
    });
}

function displayAccountInfo() {
    $("#loyaltyBalanceBox").addClass("display-none");
    $("#loyaltyErrorMessage").html("");
    if (inStorage("accountkey") && inStorage("accountnumber")) {
    } else {
        $("#loyaltyErrorMessage").text("Error: No account connected.");
        return;
    }
    apirequest(SETTINGS.apis.getaccountinfo, {
        accountnumber: getStorage("accountnumber"),
        accountkey: getStorage("accountkey")
    }, function (success) {
        $("#hasaccountbox").css("display", "");
        $("#loadingaccountbox").css("display", "none");
        if (success.status == "OK") {
            $("#loyaltyCreditBalanceHeading").text(success.credits + " points");
            $("#loyaltyBalanceBox").removeClass("display-none")
            $("#accountnumberspan").text(success.accountnumber);

            if (success.payments_setup === false) {
                $("#addPaymentMethodBox").css("display", "");
            } else {
                $("#addPaymentMethodBox").css("display", "none");
            }

            $("#accountupdateform input#name").val(success.name);
            $("#accountupdateform input#phone").val(success.phone);
            $("#accountupdateform input#email").val(success.email);
            $("#accountupdateform input#streetaddress").val(success.streetaddress);
            $("#accountupdateform input#zipcode").val(success.zipcode);
        } else {
            $("#loyaltyBalanceBox").addClass("display-none");
            $("#loyaltyErrorMessage").text("Error: " + success.msg);
        }
    }, function (xhr, status, error) {
        $("#loyaltyErrorMessage").text("Error: Couldn't get your account info. Try again later.");
        sendErrorReport("Account", "Couldn't display account info", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
    }, "GET");
}

$("body").on("click", "#setupAccountBtn", function () {
    if ($("#accountsetupform input#phonenumber").val() == "") {
        app.dialog.alert("Add your phone number.", "Error");
        return;
    }
    if ($("#accountsetupform input#name").val() == "") {
        app.dialog.alert("Add your name.", "Error");
        return;
    }
    if ($("#accountsetupform input#email").val() == "") {
        app.dialog.alert("Add your email address.", "Error");
        return;
    }
    if ($("#accountsetupform input#streetaddress").val() == "") {
        app.dialog.alert("Add your street address.", "Error");
        return;
    }
    if ($("#accountsetupform input#zipcode").val() == "") {
        app.dialog.alert("Add your ZIP Code.", "Error");
        return;
    }
    app.dialog.preloader("Creating Account...");
    apirequest(SETTINGS.apis.accountregister, {
        phone: $("#accountsetupform input#phonenumber").val(),
        name: $("#accountsetupform input#name").val(),
        email: $("#accountsetupform input#email").val(),
        address: $("#accountsetupform input#streetaddress").val(),
        zipcode: $("#accountsetupform input#zipcode").val()
    }, function (resp) {
        app.dialog.close();

        if (resp.status == "ERROR") {
            app.dialog.alert(resp.msg, "Error");
            sendErrorReport("Account", "Couldn't register account", resp.msg);
            return;
        } else {
            setStorage("accountnumber", resp.accountnumber);
            sendActionReport("Account", "Account created");
            router.refreshPage();
        }
    }, function (xhr, status, error) {
        app.dialog.close();
        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
        sendErrorReport("Account", "Couldn't register account", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
    });
});

$("body").on("click", "#updateAccountBtn", function () {
    if ($("#accountupdateform input#name").val() == "") {
        app.dialog.alert("Add your name.", "Error");
        return;
    }
    if ($("#accountupdateform input#email").val() == "") {
        app.dialog.alert("Add your email address.", "Error");
        return;
    }
    if ($("#accountupdateform input#streetaddress").val() == "") {
        app.dialog.alert("Add your street address.", "Error");
        return;
    }
    if ($("#accountupdateform input#zipcode").val() == "") {
        app.dialog.alert("Add your ZIP Code.", "Error");
        return;
    }
    app.dialog.preloader("Updating Account...");
    apirequest(SETTINGS.apis.accountregister, {
        accountnumber: getStorage("accountnumber"),
        accountkey: getStorage("accountkey"),
        name: $("#accountupdateform input#name").val(),
        phone: $("#accountupdateform input#phone").val(),
        email: $("#accountupdateform input#email").val(),
        address: $("#accountupdateform input#streetaddress").val(),
        zipcode: $("#accountupdateform input#zipcode").val()
    }, function (resp) {
        app.dialog.close();

        if (resp.status == "ERROR") {
            app.dialog.alert(resp.msg, "Error");
            sendErrorReport("Account", "Couldn't update account", resp.msg);
            return;
        } else {
            app.popup.close("#accountUpdatePopup", true);
            setStorage("accountnumber", resp.accountnumber);
            sendActionReport("Account", "Account updated");
            router.refreshPage();
            app.dialog.alert("Account details updated.", "Account Updated");
        }
    }, function (xhr, status, error) {
        app.dialog.close();
        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
        sendErrorReport("Account", "Couldn't update account", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
    });
});

$("body").on("click", "#connectExistingAccountBtn", function () {
    app.dialog.prompt("Enter your account number:", "Connect Your Account", function (val) {
        var accountnumber = val.replace(/\D/g, '');
        setStorage("accountnumber", accountnumber);
        router.refreshPage();
    }, function (cancel) {
        // shrug
    }, "");
});

$("body").on("popup:open", "#accountUpdatePopup", function () {
    app.input.checkEmptyState("#accountupdateform input#name");
    app.input.checkEmptyState("#accountupdateform input#phone");
    app.input.checkEmptyState("#accountupdateform input#email");
    app.input.checkEmptyState("#accountupdateform input#streetaddress");
    app.input.checkEmptyState("#accountupdateform input#zipcode");
});

function initAccountPage() {
    checkAccountStatus(function (result, msg) {
        switch (result) {
            case true:
                displayAccountInfo();
                break;
            case false:
                $("#setupaccountbox").css("display", "");
                $("#loadingaccountbox").css("display", "none");
                break;
            case "noauth":
                openAccountVerify(msg);
                break;
            case "badstate":
                app.dialog.alert("Your account is in an unstable state. This shouldn't happen. Please contact us at (406) 389-8988 and we'll fix it.", "Error");
                break;
            default:
                app.dialog.alert("Something went very wrong. Close the app completely (swipe it away from the app switcher) and re-open it. If you continue to get this message, contact us for help: (406) 389-8988", "Error");
                break;
        }
    });
}

function openCheckoutWindowToSaveCard(onaccountpage) {
    if (typeof onaccountpage == "undefined") {
        onaccountpage = true;
    }
    openBrowser(SETTINGS.apis.redirecttopaymentsetup
            + "?accountnumber=" + getStorage("accountnumber")
            + "&accountkey=" + getStorage("accountkey"),
            "location=yes,hidenavigationbuttons=yes,hideurlbar=yes,zoom=no,hardwareback=no,fullscreen=no,presentationstyle=pagesheet,toolbarposition=top,lefttoright=yes,toolbarcolor=#D0F2FC",
            function () {
                // on exit browser
                initAccountPage();
            },
            function (params) {
                // on get message from browser
                // only message we should get is "kill me"
                if (params.data.msg == "kill me") {
                    closeBrowser();
                }
                initAccountPage();
            }
    );

    // refresh a bit while user adds card
    setTimeout(initAccountPage, 1000 * 10);
    setTimeout(initAccountPage, 1000 * 20);
    setTimeout(initAccountPage, 1000 * 30);
    setTimeout(initAccountPage, 1000 * 40);
    setTimeout(initAccountPage, 1000 * 50);
    setTimeout(initAccountPage, 1000 * 60);
    setTimeout(initAccountPage, 1000 * 90);
    setTimeout(initAccountPage, 1000 * 120);
}

function loadReceiptHTMLIntoPopup(receiptid) {
    app.dialog.preloader("Loading...");
    apirequest(SETTINGS.apis.getreceipt, {
        accountnumber: getStorage("accountnumber"),
        accountkey: getStorage("accountkey"),
        receiptid: receiptid
    }, function (success) {
        if (success.status == "OK") {
            $('#receiptvieweriframe').attr("src", "data:text/html;base64," + btoa(success.receipt.html));
            app.popup.open("#receiptViewerPopup");
            app.dialog.close();
        } else {
            app.dialog.close();
            app.dialog.alert(success.msg, "Error");
            sendErrorReport("Receipts", "Loading receipt", success.msg);
        }
    }, function (xhr, status, error) {
        app.dialog.close();
        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
        sendErrorReport("Receipts", "Couldn't load receipt", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
    }, "POST");
}