/**
 * 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;
        document.querySelector("#name").checked       = json.name;
        document.querySelector("#first-name").checked = json.firstName;
        document.querySelector("#last-name").checked  = json.lastName;
        document.querySelector("#email").checked      = json.email;
        document.querySelector("#phone").checked      = json.phone;
        document.querySelector("#message").checked    = json.message;
    }
}

/**
 * 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() {
    // Style
    document.querySelector('#style').addEventListener('change', function (e) {
        updateSnippetHtml();
    });

    // Name
    document.querySelector('#name').addEventListener('change', function (e) {
        if (document.querySelector('#name').checked) {
            document.querySelector('#first-name').checked = false;
            document.querySelector('#last-name').checked  = false;
        } else {
            document.querySelector('#first-name').checked = true;
            document.querySelector('#last-name').checked  = true;
        }
        updateSnippetHtml();
    });

    // first name
    document.querySelector('#first-name').addEventListener('change', function (e) {
        if (document.querySelector('#first-name').checked) {
            document.querySelector('#name').checked = false;
        }
        updateSnippetHtml();
    });

    // last name
    document.querySelector('#last-name').addEventListener('change', function (e) {
        if (document.querySelector('#last-name').checked) {
            document.querySelector('#name').checked = false;
        }
        updateSnippetHtml();
    });

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

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

    // message
    document.querySelector('#message').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').value;

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

    // Name field
    if (document.querySelector('#name').checked) {
        html += `
            <div class="form-group">
                <input class="form-control"
                       name="name"
                       type="text"
                       maxlength="100"
                       data-msg-required="Please enter your name."
                       placeholder="Your Name..."
                       required
                >
            </div>
        `;
    }

    // First name field
    if (document.querySelector('#first-name').checked) {
        html += `
            <div class="form-group">
                <input class="form-control"
                       name="first_name"
                       type="text"
                       maxlength="100"
                       data-msg-required="Please enter your first name."
                       placeholder="First Name..."
                       required
                >
            </div>
        `;
    }

    // Last name field
    if (document.querySelector('#last-name').checked) {
        html += `
            <div class="form-group">
                <input class="form-control"
                       name="last_name"
                       type="text"
                       maxlength="100"
                       data-msg-required="Please enter your last name."
                       placeholder="Last Name..."
                       required
                >
            </div>
        `;
    }

    // Email field
    if (document.querySelector('#email').checked) {
        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>
        `;
    }

    // Phone field
    if (document.querySelector('#phone').checked) {
        html += `
            <div class="form-group">
                <input class="form-control"
                       name="phone"
                       type="text"
                       maxlength="100"
                       data-msg-required="Please enter your phone number."
                       placeholder="Your Phone Number..."
                       required
                >
            </div>
        `;
    }

    // Message field
    if (document.querySelector('#message').checked) {
        html += `
            <div class="form-group">
                <textarea class="form-control"
                          name="message"
                          maxlength="5000"
                          data-msg-required="Please enter your message."
                          placeholder="Your Message..."
                          required
                ></textarea>
            </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 +=
        'function generateCsrfField() {' +
        'let csrfField = document.createElement("input");' +
        'csrfField.setAttribute("type", "hidden");' +
        'csrfField.setAttribute("name", "_token");' +
        'csrfField.setAttribute("value", document.head.querySelector(\'meta[name="csrf-token"]\').content);' +
        'return csrfField;' +
        '}';

    html +=
        'function setValidation() {' +
        'var xmlhttp = new XMLHttpRequest();' +
        'xmlhttp.onreadystatechange = function() {' +
        'if (xmlhttp.readyState === XMLHttpRequest.DONE) {' +
        'if (xmlhttp.status === 200) {' +
        'let validationContainer = document.getElementById("{id}").getElementsByClassName("validation")[0];' +
        'validationContainer.innerHTML = xmlhttp.responseText;' +
        'validationContainer.prepend(generateCsrfField());' +
        '}' +
        '}' +
        '};' +
        'xmlhttp.open("GET", "/api/builder/validation", true);' +
        'xmlhttp.send();' +
        '}';

    html +=
        'var docReady = function (fn) {' +
        'var stateCheck = setInterval(function () {' +
        'if (document.readyState !== "complete") return;' +
        'clearInterval(stateCheck);' +
        'try { fn() } catch (e) { }' +
        '}, 1);' +
        '};';
    html +=
        'docReady(function () {' +
        'setValidation();' +
        '});';

    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": "' + document.querySelector("#style").value + '",' +
        '"name": ' + document.querySelector("#name").checked + ',' +
        '"firstName": ' + document.querySelector("#first-name").checked + ',' +
        '"lastName": ' + document.querySelector("#last-name").checked + ',' +
        '"email": ' + document.querySelector("#email").checked + ',' +
        '"phone": ' + document.querySelector("#phone").checked + ',' +
        '"message": ' + document.querySelector("#message").checked + '' +
        '}';

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