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


setupusername = "";
setuppassword = "";
setupsynckey = "";
setupsyncurl = "";

netsymscomurl = "https://apps.netsyms.com/account/mobile/index.php";
netsymsbizurl = "https://BIZID.netsyms.biz/accounthub/mobile/index.php";

if (localStorage.getItem("firstrun") === null) {
    $("#setuptitle").text("Setup");
    $(".firstrun-only").css("display", "");
}

$('#use-security-checkbox-li').click(function () {
    // Event fires before the checkbox is changed, so we need to do the opposite
    if ($("#use-security").prop("checked")) {
        $('#protocol-select').text("http://");
    } else {
        $('#protocol-select').text("https://");
    }
});

/* Detect if the user typed "http[s]://" into the URL box and correct for it */
$("#syncurl").blur(function () {
    if ($('#syncurl').val().toLowerCase().startsWith("https://")) {
        $('#syncurl').val($('#syncurl').val().replace(/https\:\/\//ig, ""));
        $('#protocol-select').text("https://");
        $('#use-security').prop('checked', true);
    } else if ($('#syncurl').val().toLowerCase().startsWith("http://")) {
        $('#syncurl').val($('#syncurl').val().replace(/http\:\/\//ig, ""));
        $('#protocol-select').text("http://");
        $('#use-security').prop('checked', false);
    }
});

$("#key").on("keyup", function () {
    if (window.getSelection().toString() !== '') {
        return;
    }
    var text = $('#key').val().replace(/\s+/g, '');
    var formatted = "";
    for (var i = 1; i <= text.length; i++) {
        formatted = formatted + text[i - 1];
        if (i % 5 == 0 && i > 1 && i < text.length) {
            // add a space every 5 characters,
            // unless it's the first character
            // or the last character
            formatted = formatted + " ";
        }
    }
    $('#key').val(formatted.toUpperCase());
});

$('#username').on("keyup", function () {
    $('#username').val($('#username').val().toLowerCase());
});

function manualsetup() {
    if ($('#syncurl').val().toLowerCase().startsWith("http")) {
        var syncurl = $('#syncurl').val();
    } else {
        var syncurl = $('#protocol-select').text() + $('#syncurl').val();
    }
    var username = $('#username').val();
    var key = $('#key').val().replace(/\s+/g, '');
    checkAndSave(syncurl, username, key);
}

function manualshow() {
    $('#manual_setup').css('display', 'block');
}

function checkAndSave(syncurl, username, key) {
    app.preloader.show();
    $.post(syncurl, {
        username: username,
        key: key,
        action: "check_key"
    }, function (data) {
        app.preloader.hide();
        if (data.status === 'OK') {
            setupusername = username;
            setupsyncurl = syncurl;
            setupsynckey = key;
            router.navigate({
                name: 'setup2'
            });
        } else {
            navigator.notification.alert(data.msg, null, "Error", 'Dismiss');
        }
    }, "json").fail(function () {
        app.preloader.hide();
        navigator.notification.alert("Could not connect to the server.  Try again.", null, "Error", 'Dismiss');
    });
}

function personalsetup() {
    app.preloader.show();
    var username = $("#personal_username").val();
    var password = $("#personal_password").val();

    $.post(netsymscomurl, {
        username: username,
        password: password,
        key: "NOKEY",
        desc: device.platform + " " + device.model + " " + device.serial,
        action: "generatesynccode"
    }, function (result) {
        app.preloader.hide();
        if (result.status == "OK") {
            var code = result.code;
            var accid = addaccount(username, password, netsymscomurl, code);
            switchaccount(accid, false);
            localStorage.setItem("firstrun", "1");
            navigator.notification.alert("Account connected!", null, "Success", 'Continue');
            restartApplication();
        } else if (result.status == "ERROR") {
            navigator.notification.alert(result.msg, null, "Error", 'Dismiss');
        } else {
            navigator.notification.alert("Something went wrong, please try again.", null, "Error", 'Dismiss');
        }
    }, "json").fail(function () {
        app.preloader.hide();
        navigator.notification.alert("Something went wrong, please try again.", null, "Error", 'Dismiss');
    });
}

function businesssetup() {
    app.preloader.show();
    var username = $("#personal_username").val();
    var password = $("#personal_password").val();
    var url = netsymsbizurl.replace("BIZID", $("#bizid").val());

    $.post(url, {
        username: username,
        password: password,
        key: "NOKEY",
        desc: device.platform + " " + device.model + " " + device.serial,
        action: "generatesynccode"
    }, function (result) {
        app.preloader.hide();
        if (result.status == "OK") {
            var code = result.code;
            var accid = addaccount(username, password, url, code);
            switchaccount(accid, false);
            localStorage.setItem("firstrun", "1");
            navigator.notification.alert("Account connected!", null, "Success", 'Continue');
            restartApplication();
        } else if (result.status == "ERROR") {
            navigator.notification.alert(result.msg, null, "Error", 'Dismiss');
        } else {
            navigator.notification.alert("Something went wrong, please try again.", null, "Error", 'Dismiss');
        }
    }, "json").fail(function () {
        app.preloader.hide();
        navigator.notification.alert("Something went wrong, please try again.", null, "Error", 'Dismiss');
    });

}

function scanCode() {
    try {
        cordova.plugins.barcodeScanner.scan(
                function (result) {
                    if (!result.cancelled) {
                        if (!result.text.startsWith("bizsync://")) {
                            navigator.notification.alert("Invalid sync code.  Try again.", null, "Error", 'Dismiss');
                            return;
                        }
                        var url = result.text.replace("bizsync://", "");
                        var parts = url.split("/");
                        var syncurl = parts[0].replace(/\\/g, "/");
                        var username = parts[1];
                        var key = parts[2];
                        checkAndSave(syncurl, username, key);
                    }
                },
                function (error) {
                    navigator.notification.alert("Scanning failed: " + error, null, "Error", 'Dismiss');
                },
                {
                    "showFlipCameraButton": false,
                    "prompt": "Scan mobile sync QR code."
                }
        );
    } catch (ex) {
        navigator.notification.alert(ex.message, null, "Error", 'Dismiss');
    }
}