var i = 0;
function generateSessionURL() {
    var emailRandom = "hi+" + Math.floor(Math.random() * 10000) + "@blocknify.com"
    axios({
        url: "https://easysignapi.blocknify.net/v1/documents/newDocument",
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        data: {
            "document_name": "Test document for API",
            "clientDocumentID": 5678,
            "documentByteCode": "http://easysign.blocknify.com/pdf_files/TestNDA.pdf",
            "owner_signed": false,
            "signers": [
                {
                    "email": emailRandom,
                    "sendInviteEmail": false
                }
            ],
            "note": "",
            "apiKey": "ed589d92b7d10e30f65040d3d0aed8fb",
            "hideBackground": true,
            "sendFinalEmail": false
        }
    }).then((lambdaRes) => {

        var sessionUrl = extractSessionUrl(lambdaRes);
        setIframeUrl(sessionUrl);

    }).catch((error) => {
        //this needs to be changed, but we need to provide feedback to the user that it failed. We can set up a web page.
        //another possible solution is a retry button
        console.log(error);
        console.log("out", i);
        if (i === 5) {
            var sessionUrl = "fail.html"
            setIframeUrl(sessionUrl);
            console.log(error);
            console.log("error true i =", i);
        } else {
            i = i + 1
            console.log("false i =", i);
            generateSessionURL();
        }


    })
}
function generateSessionURLEmail(email) {
    var emailRandom = "hi+" + Math.floor(Math.random() * 10000) + "@blocknify.com"
    axios({
        url: "https://easysignapi.blocknify.net/v1/documents/newDocument",
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        data: {
            "document_name": "Test document for API with invite",
            "clientDocumentID": 5678,
            "documentByteCode": "http://easysign.blocknify.com/pdf_files/TestNDA.pdf",
            "owner_signed": false,
            "signers": [
                {
                    "email": emailRandom,
                    "sendInviteEmail": false
                },
                {
                    "email": email,
                    "sendInviteEmail": true
                }
            ],
            "note": "Thank you for trying our API! This email be customized with your logo and sent from your email address. The final email will be sent after you have signed.",
            "apiKey": "ed589d92b7d10e30f65040d3d0aed8fb",
            "hideBackground": true,
            "sendFinalEmail": true
        }
    //    U2FsdGVkX1/HbdJET9OwgCRdSMP7xFgoDlQgwCYHghk=
    // ed589d92b7d10e30f65040d3d0aed8fb
    }).then((lambdaRes) => {

        var sessionUrl = extractSessionUrl(lambdaRes);
        setIframeUrl(sessionUrl);

    }).catch((error) => {
        console.log(error);
        console.log("out", i);
        if (i === 5) {
            var sessionUrl = "fail.html"
            setIframeUrl(sessionUrl);
            console.log(error);
            console.log("error true i =", i);
        } else {
            i = i + 1
            console.log("false i =", i);
            generateSessionURL();
        }


    })
}

//Extracting the session link from the lambda response
function extractSessionUrl(lambdaRes) {
    lambdaRes = JSON.parse(lambdaRes.data.body);
    console.log(lambdaRes);
    // let sessionUrl = lambdaRes.signUrls[0].sign_url;

    let url = lambdaRes.signUrls[1].sign_url;
    let n = url.lastIndexOf("on=") + 3;
    let session = url.substring(n);
    // let sessionUrl = "http://escustombranding.s3-website.eu-central-1.amazonaws.com/?session=" + session
    // let sessionUrl = "http://localhost:3000/?session=" + session
    let sessionUrl = url

    // let sessionUrl = "https://easysign.blocknify.net/?session=" + session

    return sessionUrl;
}
// console.log("test");
//Updating the iframe link
function setIframeUrl(sessionUrl) {
    let iframe = document.querySelector('iframe')
      document.getElementById("loader").style.display = "none"

    iframe.src = sessionUrl
}

let input = document.getElementById("emailApiText");
input.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("submitButton").click();
    }
});


// // Listen for iframe loaded event
// function receiveMessage(event) {
//     console.log('[parent]' + event.data);
//     document.getElementById('output').innerHTML = event.data;
//     if (event.origin !== "http://escustombranding.s3-website.eu-central-1.amazonaws.com")
//         return
//     console.log('[parent] not right host' + event.data);
// }
// Calling the function every time someone visits this page
// generateSessionURL();

console.log("test");

// Listen for iframe loaded event
// window.addEventListener("message", receiveMessage, false);