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

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

        // Display the custom variables on the checkbox and input text
        document.querySelector("#type").value = json.type;
        document.querySelector("#items").value = json.items;
        document.querySelector("#style").value = json.style;
        document.querySelector("#margin").value = json.margin;
        document.querySelector("#loop").checked = json.loop;
        document.querySelector("#nav").checked = json.nav;
        document.querySelector("#dots").checked = json.dots;
        document.querySelector("#speed").value = json.speed;
        document.querySelector("#autoplay").checked = json.autoplay;
        document.querySelector("#pause").checked = json.autoplay_pause;

        document.querySelector("#show-title").checked = json.show_title;
        document.querySelector("#number-characters").value = json.number_characters;
        document.querySelector("#number-reviews").value = json.number_reviews;
    }
}

/**
 * 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() {

    // Type
    document.querySelector('#type').addEventListener('change', function (e) {
        if (document.querySelector('#type').value === 'slider') {
            document.querySelector('#items').value = 1;
        } else {
            document.querySelector('#items').value = 4;
        }
        updateSnippetHtml();
    });

    // Items
    document.querySelector('#items').addEventListener('change', function (e) {
        if (document.querySelector('#items').value > 1) {
            document.querySelector('#type').value = 'carousel';
        } else {
            document.querySelector('#type').value = 'slider';
        }
        updateSnippetHtml();
    });

    // Style
    document.querySelector('#style').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Margin
    document.querySelector('#margin').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Loop
    document.querySelector('#loop').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Nav
    document.querySelector('#nav').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Dots
    document.querySelector('#dots').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // speed
    document.querySelector('#speed').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Autoplay
    document.querySelector('#autoplay').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Autoplay pause
    document.querySelector('#pause').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Show title
    document.querySelector('#show-title').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Number of characters
    document.querySelector('#number-characters').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Number of characters
    document.querySelector('#number-reviews').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 id = makeId();
    let html = '';

    let style = document.querySelector('#style').value;
    let type = document.querySelector('#type').value;

    let itemsOnMobile = 1;
    let itemsOnTablet = (document.querySelector("#type").value === "slider") ? 1 : 3;
    let itemsOnDesktop = document.querySelector("#items").value;
    let speed = document.querySelector("#speed").value;

    let showTitle = document.querySelector("#show-title").checked;
    let numberCharacters = document.querySelector("#number-characters").value;
    let numberReviews = document.querySelector("#number-reviews").value;

    let endpoint = `/api/builder/review?title=${showTitle}`;

    if (numberCharacters) {
        endpoint += `&characters=${numberCharacters}`;
    }
    if (numberReviews) {
        endpoint += `&limit=${numberReviews}`;
    }

    // The ajax container for the slides
    html += `
        <div
            id="${id}"
            class="bongo-carousel owl-theme bongo-reviews ${type} ${style}"
            data-type="${type}"
            data-style="${style}"
            data-per-view="${itemsOnDesktop}"
            data-per-view-mobile="${itemsOnMobile}"
            data-per-view-tablet="${itemsOnTablet}"
            data-per-view-desktop="${itemsOnDesktop}"
            data-no-of-chars="${numberCharacters}"
            data-no-of-reviews="${numberReviews}"
            data-speed="${speed}"
        ></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) {

                        var reviewContainer = document.getElementById("${id}");
                        reviewContainer.innerHTML = xmlhttp.responseText;

                        var clones = document.querySelectorAll(".cloned");
                        Array.prototype.forEach.call(clones, function(clone) {
                            clone.removeAttribute("data-subblock");
                            clone.childNodes[0].removeAttribute("data-subblock");
                        });

                        var slider = $("#${id}").owlCarousel({
                            items: ${itemsOnDesktop},
                            margin: ${document.querySelector("#margin").value},
                            loop: ${document.querySelector("#loop").checked},
                            nav: ${document.querySelector("#nav").checked},
                            dots: ${document.querySelector("#dots").checked},
                            smartSpeed: ${speed},
                            fluidSpeed: ${speed},
                            autoplay: ${document.querySelector("#autoplay").checked},
                            autoplayHoverPause: ${document.querySelector("#pause").checked},
                            responsiveClass: true,
                            responsive: {
                                0: {
                                    items: ${itemsOnMobile}
                                },
                                768: {
                                    items: ${itemsOnTablet}
                                },
                                960: {
                                    items: ${itemsOnDesktop}
                                }
                            }
                        });

                        if (document.querySelector("#page-builder") || document.querySelector("#post-builder")) {
                            slider.data('owl.carousel').options.loop = false;
                            slider.data('owl.carousel').options.autoplay = false;
                            slider.trigger('refresh.owl.carousel');
                        }

                        document.querySelector("#${id}").style.display = "block";
                    }
                }
            };
            xmlhttp.open("GET", "${endpoint}", 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);

    // We also put the custom variables on the snippet by calling setSettings() method.
    let settings = `{
        "type": "${document.querySelector("#type").value}",
        "items": ${document.querySelector("#items").value},
        "style": "${document.querySelector("#style").value}",
        "margin": ${document.querySelector("#margin").value},
        "loop": ${document.querySelector("#loop").checked},
        "nav": ${document.querySelector("#nav").checked},
        "dots": ${document.querySelector("#dots").checked},
        "speed": "${document.querySelector("#speed").value}",
        "autoplay": ${document.querySelector("#autoplay").checked},
        "autoplay_pause": ${document.querySelector("#pause").checked},

        "show_title": ${document.querySelector("#show-title").checked},
        "number_characters": "${document.querySelector("#number-characters").value}",
        "number_reviews": "${document.querySelector("#number-reviews").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);
        };
    `;
}

/**
 * @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();
