/**
 * Restore the saved settings
 *
 * This page is opened when you click settings icon on the snippet. In this page, we will modify custom variables.
 * Custom variables are data that be used for any purpose. For example, on a slider snippet, custom variables
 * are used to store the url of the images and also other slider settings that user can change.
 * Ini this example, we have a checkbox and an input text as example on how to interact with custom variables.
 * That's why custom variables are stored (in snippet) in a data attribute named data-settings,
 * because custom variables can control the snippet content.
 * Get custom variables by reading data-settings attribute defined on snippet => see minimalist-blocks/content.js
 */
function restoreSavedSettings() {
    let settings = getSettings();
    if (settings !== 'undefined') {
        let json = JSON.parse(settings);
        document.querySelector("#ref").value = json.ref;
    }
}

/**
 * Register form events
 *
 * When user make any change to the value, call updateSnippetHtml() function
 * updateSnippetHtml() function generates HTML content to be displayed on the snippet.
 */
function registerFormEvents() {
    document.querySelector('#ref').addEventListener('change', function (e) {
        updateSnippetHtml();
    });
}

/**
 * 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
    html += `<div id="${id}" class="menu-builder"></div>`;

    // Append the javascript
    html += '<scr' + 'ipt>';
    html += getMenuScript(id);
    html += getDocumentReadyScript();
    html += `
        docReady(function () {
            getMenu();
        });
    `;
    html += '</scr' + 'ipt>';

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

    // We also put the custom variables on the snippet by calling setSettings() method.
    let settings = '{' +
        '"ref": "' + document.querySelector("#ref").value + '"' +
        '}';

    setSettings(settings);
}

/**
 * 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);
        };
    `;
}

/**
 * Get the form script
 */
function getMenuScript(id) {
    let script = '';
    let ref = document.querySelector("#ref").value;
    let endpoint = `/api/builder/menu-builder?ref=${ref}`;

    script += `
        function getMenu() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState === XMLHttpRequest.DONE) {
                    if (xmlhttp.status === 200) {
                        let menuContainer = document.getElementById("${id}");
                        menuContainer.innerHTML = xmlhttp.responseText;  
                        
                        if (document.body.classList.contains("web-editor")) {
                            var anchors = document.getElementsByClassName("nav-link");
                            if (anchors.length > 0) {
                                for (var i = 0; i < anchors.length; i++) {
                                    anchors[i].style = "pointer-events: none; cursor: default;";
                                }
                            }
                        }                      
                    }
                }
            };
            xmlhttp.open("GET", "${endpoint}", true);
            xmlhttp.send();
        }
    `;

    return script;
}

/**
 * Get the active module
 */
function getActiveModule() {
    return parent.document.querySelector("[data-module-active]");
}

/**
 *
 * @returns {string}
 */
function getSettings() {
    let activeModule = getActiveModule(); //get active module
    return decodeURIComponent(activeModule.getAttribute('data-settings'));
}

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

/**
 *
 * @param settings
 */
function setSettings(settings) {
    parent.document.querySelector('#hidContentModuleSettings').value = settings;
}

/**
 * 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;
}

// restore any saved settings
restoreSavedSettings();

// Register the events
registerFormEvents();

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