/**
 * 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
        if (document.querySelector("#style")) {
            document.querySelector("#style").value = json.style || 'form-inline';
        }
        if (document.querySelector("#button-style")) {
            document.querySelector("#button-style").value = json.button_style || 'btn-primary';
        }
        if (document.querySelector("#name")) {
            document.querySelector("#name").checked = json.name || false;
        }
        if (document.querySelector("#first-name")) {
            document.querySelector("#first-name").checked = json.firstName || false;
        }
        if (document.querySelector("#last-name")) {
            document.querySelector("#last-name").checked = json.lastName || false;
        }
        if (document.querySelector("#email")) {
            document.querySelector("#email").checked = json.email || false;
        }
        if (document.querySelector("#phone")) {
            document.querySelector("#phone").checked = json.phone || false;
        }
        if (document.querySelector("#message")) {
            document.querySelector("#message").checked = json.message || false;
        }
    }
}

/**
 * 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() {
    if (document.querySelector("#style")) {
        document.querySelector('#style')
            .addEventListener('change', function (e) {
                updateSnippetHtml();
            });
    }
    if (document.querySelector("#button-style")) {
        document.querySelector('#button-style')
            .addEventListener('change', function (e) {
                updateSnippetHtml();
            });
    }
    if (document.querySelector("#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();
            });
    }
    if (document.querySelector("#first-name")) {
        document.querySelector('#first-name')
            .addEventListener('change', function (e) {
                if (document.querySelector('#first-name').checked) {
                    document.querySelector('#name').checked = false;
                }
                updateSnippetHtml();
            });
    }
    if (document.querySelector("#last-name")) {
        document.querySelector('#last-name')
            .addEventListener('change', function (e) {
                if (document.querySelector('#last-name').checked) {
                    document.querySelector('#name').checked = false;
                }
                updateSnippetHtml();
            });
    }
    if (document.querySelector("#email")) {
        document.querySelector('#email')
            .addEventListener('change', function (e) {
                updateSnippetHtml();
            });
    }
    if (document.querySelector("#phone")) {
        document.querySelector('#phone')
            .addEventListener('change', function (e) {
                updateSnippetHtml();
            });
    }
    if (document.querySelector("#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 name = document.querySelector('#name')
        ? document.querySelector('#name').checked
        : false;

    let firstName = document.querySelector('#first-name')
        ? document.querySelector('#first-name').checked
        : false;

    let lastName = document.querySelector('#last-name')
        ? document.querySelector('#last-name').checked
        : false;

    let email = document.querySelector('#email')
        ? document.querySelector('#email').checked
        : false;

    let phone = document.querySelector('#phone')
        ? document.querySelector('#phone').checked
        : false;

    let message = document.querySelector('#message')
        ? document.querySelector('#message').checked
        : false;

    let style = document.querySelector('#style')
        ? document.querySelector('#style').value
        : 'form-inline';

    let buttonStyle = document.querySelector('#button-style')
        ? document.querySelector('#button-style').value
        : 'btn-primary';

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

    // Fields to display
    if (name) {
        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>
        `;
    }
    if (firstName) {
        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>
        `;
    }
    if (lastName) {
        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>
        `;
    }
    if (email) {
        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>
        `;
    }
    if (phone) {
        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>
        `;
    }
    if (message) {
        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="form-submit btn ${buttonStyle} font-weight-bold text-uppercase"
                   type="submit"
            >
                Submit
            </button>
        </div>
    `;

    html += `</form>`;

    // Append the JavaScript, concatenation is to stop it running early
    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}", 'enquiry');
            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}",
        "button_style": "${buttonStyle}",
        "name": ${name},
        "firstName": ${firstName},
        "lastName": ${lastName},
        "email": ${email},
        "phone": ${phone},
        "message": ${message}
    }`;

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