
let pageUri = window.location.origin + '/WebServices/MachPanelService.asmx';

let MSG_CONST = {
    serverRequestError: 'Request to server failed',
    loggingIn: 'Logging In...',
    pleaseWait: 'Please wait.',
    credVerifyFailed: 'Credential verification failed',
    unknownError: 'Something wen\'t really wrong',
    registering: 'Registering...',
    clientCredsCreateError: 'Could not create credentials in browser. Probably because the username is already registered with your authenticator. Please change username or authenticator (biometric, pin or key).',
    registerSuccessTitle: 'Registration Successful!',
    registerSuccessText: 'You\'ve registered successfully.',
    loginSuccessTitle: 'Logged In!',
    loginSuccessText: 'You\'ve logged in successfully!'
};

async function getMessageStringConstants() {

    try {

        var res = await fetch(pageUri + '/getPasswordlessMessageConstants', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json; charset=UTF-8'
            }
        });

        let jRes = await res.json();
        return JSON.parse(jRes.d)
    } catch (e) {
        console.warn('Error in fetching string constants for passwordless authentication', e);
    }
}

window.addEventListener("load", (e) => {
    setTimeout(async () => { MSG_CONST = await getMessageStringConstants(); }, 1000);
});

coerceToArrayBuffer = function (thing, name) {
    if (typeof thing === "string") {
        // base64url to base64
        thing = thing.replace(/-/g, "+").replace(/_/g, "/");

        // base64 to Uint8Array
        var str = window.atob(thing);
        var bytes = new Uint8Array(str.length);
        for (var i = 0; i < str.length; i++) {
            bytes[i] = str.charCodeAt(i);
        }
        thing = bytes;
    }

    // Array to Uint8Array
    if (Array.isArray(thing)) {
        thing = new Uint8Array(thing);
    }

    // Uint8Array to ArrayBuffer
    if (thing instanceof Uint8Array) {
        thing = thing.buffer;
    }

    // error if none of the above worked
    if (!(thing instanceof ArrayBuffer)) {
        throw new TypeError("could not coerce '" + name + "' to ArrayBuffer");
    }

    return thing;
};


coerceToBase64Url = function (thing) {
    // Array or ArrayBuffer to Uint8Array
    if (Array.isArray(thing)) {
        thing = Uint8Array.from(thing);
    }

    if (thing instanceof ArrayBuffer) {
        thing = new Uint8Array(thing);
    }

    // Uint8Array to base64
    if (thing instanceof Uint8Array) {
        var str = "";
        var len = thing.byteLength;

        for (var i = 0; i < len; i++) {
            str += String.fromCharCode(thing[i]);
        }
        thing = window.btoa(str);
    }

    if (typeof thing !== "string") {
        throw new Error("could not coerce to string");
    }

    // base64 to base64url
    // NOTE: "=" at the end of challenge is optional, strip it off here
    thing = thing.replace(/\+/g, "-").replace(/\//g, "_").replace(/=*$/g, "");

    return thing;
};



// HELPERS

function showDemoAlert() {

    let timerInterval
    Swal.fire({
        title: 'Auto close alert!',
        html: 'I will close in <b></b> seconds.',
        timer: 10000,
        timerProgressBar: true,
        didOpen: () => {
            Swal.showLoading()
            const b = Swal.getHtmlContainer().querySelector('b')
            timerInterval = setInterval(() => {
                b.textContent = parseInt(Swal.getTimerLeft() / 1000) + 1
            }, 1000)
        },
        willClose: () => {
            clearInterval(timerInterval)
        }
    });//.then((result) => {
    /* Read more about handling dismissals below */
    //if (result.dismiss === Swal.DismissReason.timer) {
    //    console.log('I was closed by the timer')
    //}
    //});

}

function showErrorAlert(message, error, callback) {

    let footermsg = '';
    if (error) {
        footermsg = 'exception:' + error.toString();
        console.error(footermsg);
    }

    Swal.fire({
        //type: 'error',
        title: 'Error',
        text: message,
        footer: footermsg,
        //footer: '<a href>Why do I have this issue?</a>'
    }).then((res) => { if (callback) callback(); })
}

function detectFIDOSupport() {
    if (window.PublicKeyCredential === undefined ||
        typeof window.PublicKeyCredential !== "function") {
        //$('#register-button').attr("disabled", true);
        //$('#login-button').attr("disabled", true);
        var el = document.getElementById("notSupportedWarning");
        if (el) {
            el.style.display = 'block';
        }
        return;
    }
}

/**
 * 
 * Get a form value
 * @param {any} selector
 */
function value(selector) {
    var el = document.querySelector(selector);
    if (el.type === "checkbox") {
        return el.checked;
    }
    return el.value;
}

function toCamelCase(o) {
    var newO, origKey, newKey, value
    if (o instanceof Array) {
        return o.map(function (value) {
            if (typeof value === "object") {
                value = toCamelCase(value)
            }
            return value
        })
    } else {
        newO = {}
        for (origKey in o) {
            if (o.hasOwnProperty(origKey)) {
                newKey = (origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey).toString()
                value = o[origKey]
                if (value instanceof Array || (value !== null && value.constructor === Object)) {
                    value = toCamelCase(value)
                }
                newO[newKey] = value
            }
        }
    }
    return newO
}