/// <reference path="helpers.js" />
//let pageUri = window.location.origin + '/WebServices/MachPanelService.asmx';

//console.logpageUri);
//document.getElementById('btn-register-sec-creds').addEventListener('submit', handleRegisterSubmit);

let onRegisterSuccessCallback = () => {
    if (window.location.href.includes("SecCredAddok=1"))
        window.location.href = window.location.href + " ";
    else if (window.location.href.includes("?"))
        window.location.href = window.location.href + "&SecCredAddok=1"
    else
        window.location.href = window.location.href + "?SecCredAddok=1"
};

async function handleRegisterSubmit(event) {

    event.preventDefault();

    let username = '';
    let displayName = '';
    let accountType = '';
    let accountId = '';

    if (this && this.username)
        username = this.username.value;
    else {
        username = $('input[type="hidden"][id$="HF_UserName"]').val()
    }

    if (this && this.displayName)
        displayName = this.displayName.value;
    else {
        displayName = $('input[type="hidden"][id$="HF_DisplayName"]').val()
    }

    if (this && this.accountType)
        accountType = this.accountType.value;
    else {
        accountType = $('input[type="hidden"][id$="HF_AccountType"]').val()
    }

    if (this && this.accountId)
        accountId = this.accountId.value;
    else {
        accountId = $('input[type="hidden"][id$="HF_AccountId"]').val()
    }


    // possible values: none, direct, indirect
    let attestation_type = "none";
    // possible values: <empty>, platform, cross-platform
    let authenticator_attachment = "platform";

    // possible values: preferred, required, discouraged
    let user_verification = "preferred";

    // possible values: discouraged, preferred, required
    let residentKey = "discouraged";

    var data = {
        'userName': username,
        'displayName': displayName,
        'attType': attestation_type,
        'authType': authenticator_attachment,
        'userVerification': user_verification,
        'residentKey': residentKey,
        'accountType': accountType,
        'accountId': accountId
    };

    $('.page-loader-wrapper').show();

    //console.log'data', data);
    // send to server for registering
    let makeCredentialOptions;
    try {
        makeCredentialOptions = await fetchMakeCredentialOptions(data);
    } catch (e) {
        //console.error(e);
        let msg = MSG_CONST.unknownError;

        $('.page-loader-wrapper').hide();

        showErrorAlert(msg, e);
    }


    //console.log"Credential Options Object: ", makeCredentialOptions);
    if (makeCredentialOptions.status !== "ok") {

        $('.page-loader-wrapper').hide();

        //console.log"Error creating credential options: ", makeCredentialOptions.errorMessage);
        showErrorAlert(makeCredentialOptions.errorMessage);
        return;
    }

    // Turn the challenge back into the accepted format of padded base64
    makeCredentialOptions.challenge = coerceToArrayBuffer(makeCredentialOptions.challenge);
    // Turn ID into a UInt8Array Buffer for some reason
    makeCredentialOptions.user.id = coerceToArrayBuffer(makeCredentialOptions.user.id);

    makeCredentialOptions.excludeCredentials = makeCredentialOptions.excludeCredentials.map((c) => {
        c.id = coerceToArrayBuffer(c.id);
        return c;
    });

    if (makeCredentialOptions.authenticatorSelection.authenticatorAttachment === null) makeCredentialOptions.authenticatorSelection.authenticatorAttachment = undefined;

    //console.log"Credential Options Formatted", makeCredentialOptions);

    Swal.fire({
        title: MSG_CONST.registering,
        text: MSG_CONST.pleaseWait,
        //imageUrl: "/images/securitykey.min.svg",
        showCancelButton: false,
        showConfirmButton: false,
        focusConfirm: false,
        focusCancel: false
    });


    //console.log"Creating PublicKeyCredential...", makeCredentialOptions);

    let newCredential;
    try {
        newCredential = await navigator.credentials.create({
            publicKey: makeCredentialOptions
        });
    } catch (e) {
        var msg = MSG_CONST.clientCredsCreateError;
        console.error(msg, e);

        $('.page-loader-wrapper').hide();

        showErrorAlert(msg, e);
    }


    //console.log"PublicKeyCredential Created", newCredential);
    if (newCredential && newCredential.response && newCredential.response.attestationObject)
        try {
            registerNewCredential(newCredential);//.then(setTimeout(() => { onRegisterSuccessCallback() },3000));
        } catch (e) {

            $('.page-loader-wrapper').hide();

            showErrorAlert(err.message ? err.message : err);
        }
    $('.page-loader-wrapper').hide();
}

async function fetchMakeCredentialOptions(formData) {
    let dataStr = JSON.stringify(formData);
    let response = await fetch(pageUri + '/makeCredentialOptions', {
        method: 'POST', // or 'PUT'
        body: dataStr, // data can be `string` or {object}!,
        headers: {
            'Accept': 'application/json',
            'Content-Type': "application/json; charset=utf-8"
        }
    });
    let data = await response.json();
    return JSON.parse(data.d);
}


// This should be used to verify the auth data with the server
async function registerNewCredential(newCredential) {
    // Move data into Arrays incase it is super long
    let attestationObject = new Uint8Array(newCredential.response.attestationObject);
    let clientDataJSON = new Uint8Array(newCredential.response.clientDataJSON);
    let rawId = new Uint8Array(newCredential.rawId);

    const data = {
        id: newCredential.id,
        rawId: coerceToBase64Url(rawId),
        type: newCredential.type,
        extensions: newCredential.getClientExtensionResults(),
        response: {
            AttestationObject: coerceToBase64Url(attestationObject),
            clientDataJson: coerceToBase64Url(clientDataJSON)
        }
    };

    let response;
    try {

        response = await registerCredentialWithServer(data);
    } catch (e) {

        $('.page-loader-wrapper').hide();

        showErrorAlert(e);
    }

    //console.log"Credential Object", response);

    // show error
    if (response.status !== "ok") {
        //console.log"Error creating credential");
        //console.logresponse.errorMessage);

        $('.page-loader-wrapper').hide();

        showErrorAlert(response.errorMessage);
        return;
    }

    // show success 
    Swal.fire({
        title: MSG_CONST.registerSuccessTitle,
        text: MSG_CONST.registerSuccessText,
        type: 'success',
    }).then((res) => { onRegisterSuccessCallback(); });

    // redirect to dashboard?
    //window.location.href = "/dashboard/";// + state.user.displayName;
}



async function registerCredentialWithServer(formData) {

    let data = {};
    data.attestationResponse = formData;
    let response = await fetch(pageUri + '/makeCredential', {
        method: 'POST', // or 'PUT'
        body: JSON.stringify(data), // data can be `string` or {object}!
        headers: {
            'Accept': 'application/json',
            'Content-Type': "application/json; charset=utf-8"
        }
    });

    data = await response.json();

    return JSON.parse(data.d);
}
