/**
 * Generate html content.
 *
 * Here you can use the custom variables.
 * Also you can embed custom javascript.
 * Here you can also create a unique ID {id} so that multiple snippets won;t be a problem.
 */
function updateSnippetHtml() {

    let html  = '';
    let id    = makeId();

    // The ajax container for the slides
    html += `<div id="${id}" class="review-summary"></div>`;

    // Append the javascript
    html += '<scr' + 'ipt>';
    html += getDocumentReadyScript();
    html += `
        docReady(function () {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState === XMLHttpRequest.DONE) {
                    if (xmlhttp.status === 200) {
                        let summaryContainer = document.getElementById("${id}");
                        summaryContainer.innerHTML = xmlhttp.responseText;
                    }
                }
            };
            xmlhttp.open("GET", "/api/builder/review-summary", true);
            xmlhttp.send();
        });
    `;
    html += '</scr' + 'ipt>';

    // After generate the html, put the html on the snippet by calling setHtml() method. This will render the content.
    setHtml(html);
}

/**
 * Get document ready script
 */
function getDocumentReadyScript() {
    return `
        var docReady = function (fn) {
            var stateCheck = setInterval(function () {
                if (document.readyState !== "complete") return;
                clearInterval(stateCheck);
                try { fn() } catch (e) { }
            }, 1);
        };
    `;
}

/**
 *
 * @param html
 */
function setHtml(html) {
    parent.document.querySelector('#hidContentModuleCode').value = html;
}

/**
 * http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript
 * @returns {string}
 */
function makeId() {
    let text     = "";
    let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    for (let i = 0; i < 2; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    let text2     = "";
    let possible2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (let i = 0; i < 5; i++)
        text2 += possible2.charAt(Math.floor(Math.random() * possible2.length));

    return text + text2;
}

// Update the html for the snippet
updateSnippetHtml();