/**
 * 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("#style").value = json.style;
    }
}

/**
 * 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('#style').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 style = document.querySelector('#style')
        ? document.querySelector('#style').value
        : 'form-block';

    html += `
        <form id="{id}" class="builder-form ${style}" action="/reviews/store" method="POST">
            <div class="validation" style="display: none;"></div>
    `;

    // Title field
    html += `
        <div class="form-group">
            <input class="form-control"
                   name="title"
                   type="text"
                   maxlength="100"
                   data-msg-required="Please enter your opinion."
                   placeholder="Your opinion in one sentence..."
                   required
            >
        </div>
    `;

    // Content field
    html += `
        <div class="form-group">
            <textarea class="form-control"
                      name="content"
                      maxlength="5000"
                      data-msg-required="Please enter your review."
                      placeholder="Your full review..."
                      required
            ></textarea>
        </div>
    `;

    // Rating field
    html += `
        <div class="form-group">
            <select class="form-control" name="rating" required>
                <option value="1">1 Star</option>
                <option value="2">2 Star</option>
                <option value="3">3 Star</option>
                <option value="4">4 Star</option>
                <option value="5" selected="selected">5 Star</option>
            </select>
        </div>
    `;

    // Name field
    html += `
        <div class="form-group">
            <input class="form-control"
                   name="name"
                   type="text"
                   maxlength="100"
                   value=""
                   data-msg-required="Please enter your full name."
                   placeholder="Your Name..."
                   required
            >
        </div>
    `;

    // Email field
    html += `
        <div class="form-group">
            <input class="form-control"
                   name="email"
                   type="email"
                   maxlength="100"
                   data-msg-required="Please enter your email address."
                   data-msg-email="Please enter a valid email address."
                   placeholder="Your Email Address..."
                   required
            >
        </div>
    `;

    // Submit button
    html += `
        <div class="form-group">
            <button
                class="btn btn-xl btn-outline btn-primary text-1 font-weight-bold text-uppercase"
                type="submit"
            >
                Submit
            </button>
        </div>
    `;

    html += `</form>`;

    // Append the javascript
    html += '<scr' + 'ipt>';
    html += `
        var docReady{id} = function (fn) {
            var stateCheck = setInterval(function () {
                if (document.readyState !== "complete") return;
                clearInterval(stateCheck);
                try {fn()} catch (e) {}
            }, 1000);
        };
        docReady{id}(function () {
            let validationRequest{id} = new ValidationRequest("{id}");
            validationRequest{id}.init();
        });
    `;
    html += '</scr' + 'ipt>';

    html = html.replace(/{id}/g, makeId());

    // 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 = `{
        "style": "${style}"
    }`;

    setSettings(settings);
}

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