/*
 * 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 deleteAllSettings() {
    navigator.notification.confirm("Really wipe user data?  You will need to resync the app with AccountHub to use it again.  This will not delete 2-factor auth keys.", function (result) {
        if (result != 1) {
            return;
        }
        // Wipe localStorage
        localStorage.removeItem("username");
        localStorage.removeItem("password");
        localStorage.removeItem("syncurl");
        localStorage.removeItem("key");
        localStorage.removeItem("accounts");
        NativeStorage.remove("accounts", function () {
            // force-reload app
            navigator.notification.alert("All connection data and credentials erased.", function () {
                restartApplication();
            }, "App Reset", 'Continue');
        });
    }, "Are you sure?");
}

/**
 * Prompts the user to enter their password, then checks the password and
 * saves or displays an error.
 * @returns {undefined}
 */
function updatePassword() {
    navigator.notification.prompt("Re-enter your password.", function (results) {
        if (results.buttonIndex == 1) {
            $.post(localStorage.getItem("syncurl"), {
                username: localStorage.getItem("username"),
                key: localStorage.getItem("key"),
                password: results.input1,
                action: "check_password"
            }, function (data) {
                if (data.status === 'OK') {
                    localStorage.setItem("password", results.input1);
                    passwd(results.input1);
                    navigator.notification.alert("Saved password updated.", function () {
                        // Reload app just to be safe
                        restartApplication();
                    }, "Success", 'Continue');
                } else {
                    navigator.notification.alert(data.msg, null, "Error", 'Dismiss');
                }
            }, "json").fail(function () {
                navigator.notification.alert("Could not connect to the server.  Try again later.", null, "Error", 'Dismiss');
            });
        }
    }, "Update Password", ["Save", "Cancel"]);
}

function updateSettingsData() {
    cordova.getAppVersion.getVersionNumber(function (version) {
        $('#app_version').text(version);
    });
    cordova.getAppVersion.getPackageName(function (package) {
        $('#app_package').text(package);
    });
    cordova.getAppVersion.getVersionCode(function (version) {
        $('#app_version_code').text(version);
    });
    if (localStorage.getItem("username")) {
        $("#username").text(localStorage.getItem("username"));
    }
    if (localStorage.getItem("key")) {
        var key = localStorage.getItem("key");
        var stars = "";
        for (var i = 0; i < key.length - 6; i++) {
            stars += "*";
        }
        $("#pairingkey").text(key.slice(0, 3) + stars + key.slice(-3));
    }
    if (localStorage.getItem("syncurl")) {
        $("#syncurl").text(localStorage.getItem("syncurl").replace("/mobile/index.php", ""));
    }
}

function getSettingsTemplateData() {
    return [
        {
            setting: "userinfo",
            title: '<i class="fa fa-user"></i> <span id="username">Not logged in</span>',
            text: '<i class="fa fa-key"></i> Pairing Code: <span id="pairingkey">None</span><br /><i class="fa fa-server"></i> Server: <span id="syncurl">None</span>',
            onclick: ""
        },
        {
            setting: "accounts",
            title: "Manage and switch accounts",
            onclick: "openAccountSwitcher(false)"
        },
        {
            setting: "updatepassword",
            title: "Update Password",
            text: "Enter your new password if you changed it from AccountHub.",
            onclick: "updatePassword()"
        },
        {
            setting: "deleteall",
            title: "Disconnect All Accounts",
            text: "Forget all account data for all connected accounts and open the setup tool.",
            onclick: "deleteAllSettings()"
        },
        {
            setting: "versions",
            title: "Netsyms Apps for Mobile</span> v<span id=\"app_version\">2.x</span>",
            text: "Copyright &copy; 2018 Netsyms Technologies.  License: <span style=\"text-decoration: underline;\" onclick=\"window.open('https://source.netsyms.com/Business/MobileApp?pk_campaign=NetsymsMobile-SystemBrowser', '_system', '');\">Mozilla Public License 2.0</span>.",
            onclick: ""
        },
        {
            setting: "opensource",
            title: "Open Source Information",
            text: "",
            onclick: "router.navigate('/credits')"
        },
        {
            setting: "privacy",
            title: "Privacy Policy",
            text: "",
            onclick: "cordova.InAppBrowser.open('https://netsyms.com/legal?pk_campaign=NetsymsMobile-SystemBrowser', '_blank', 'location=yes')"
        }
    ];
}

function loadSettingsPage() {
    router.navigate("/settings", {
        context: {
            settings: getSettingsTemplateData()
        },
    });
    updateSettingsData();
}