const Helper = {
    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;
    },
    addClass(element, classname) {
        if (! element) {
            return;
        }

        if (Helper.hasClass(element, classname)) {
            return;
        }

        if (element.classList.length === 0) {
            element.className = classname;
        } else {
            element.className = element.className + ' ' + classname;
        }

        element.className = element.className.replace(/  +/g, ' ');
    },
    hasClass(element, classname) {
        if (! element) {
            return false;
        }

        if (element.classList) {
            return element.classList.contains(classname);
        }

        return new RegExp('\\b' + classname + '\\b').test(element.className);
    },
    removeClass(element, classname) {
        if (! element) {
            return;
        }

        if (element.classList.length > 0) {
            element.className = element.className.replace(classname, '');
        }
    },
    isNumber(evt) {
        evt = (evt) ? evt : window.event;

        let charCode = (evt.which) ? evt.which : evt.keyCode;

        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }

        return true;
    },
    isBlank(string) {
        return ! string
            || /^\s*$/.test(string)
            || string.length === 0
            || string === 'null'
            || string === '/edit/null';
    }
};

const Module = {
    get() {
        return parent.document.querySelector("[data-module-active]");
    }
};

const Settings = {
    get() {
        return decodeURIComponent(
            Module.get().getAttribute('data-settings')
        );
    },
    save() {
        let updatedSettings = `{
            "style": "${ModalForm.fields.style.get().value}",
            "button_style": "${ModalForm.fields.button_style.get().value}"
        }`;
        updatedSettings = updatedSettings.replace(/ +(?= )/g, '').trim();

        parent.document.querySelector('#hidContentModuleSettings').value = updatedSettings;
    },
    restore() {
        let savedSettings = this.get();
        if (savedSettings !== 'undefined') {

            let jsonData = JSON.parse(savedSettings);
            ModalForm.fields.style.set(jsonData.style);
            ModalForm.fields.button_style.set(jsonData.button_style);
        }
    }
}

const ModalForm = {
    register() {
        this.fields.style.restore();
        this.fields.button_style.restore();

        this.fields.style.events();
        this.fields.button_style.events();
    },
    fields: {
        style: {
            get() {
                return document.querySelector('#style');
            },
            set(value) {
                this.get().value = value;
            },
            restore() {
                Snippet.update();
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        button_style: {
            get() {
                return document.querySelector('#button-style');
            },
            set(value) {
                this.get().value = value;
            },
            restore() {
                Snippet.update();
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        }
    },
}

const Snippet = {
    getDocumentReadyScript(id) {
        return `
            var docReady${id} = function (fn) {
                var stateCheck = setInterval(function () {
                    if (document.readyState !== "complete") return;
                    clearInterval(stateCheck);
                    try { fn() } catch (e) { }
                }, 1);
            };
        `;
    },
    getHtml(id) {
        let route = '/estimate/search';
        let style = ModalForm.fields.style.get().value;
        let buttonStyle = ModalForm.fields.button_style.get().value;
        let buttonText = 'Search';

        let line1Placeholder = 'e.g. 48, common rd';
        let postcodePlaceholder = 'e.g B78 0AB';

        let html = '';

        html += `
            <form
                id="${id}"
                class="estimate-form has-captcha ${style}"
                action="${route}"
                method="POST"
                data-style="${style}"
                data-button-style="${buttonStyle}"
            >
                <div class="validation"></div>
        `;

        // Line 1
        html += `
            <div class="form-group">
                <input
                    class="form-control"
                    name="line_1"
                    type="text"
                    maxlength="50"
                    placeholder="${line1Placeholder}"
                    autocomplete="line-1"
                    required
                >
            </div>
        `;

        // Postcode
        html += `
            <div class="form-group">
                <input
                    class="form-control"
                    name="postcode"
                    type="text"
                    maxlength="10"
                    placeholder="${postcodePlaceholder}"
                    autocomplete="postal-code"
                    required
                >
            </div>
        `;

        // Submit button
        html += `
            <div class="form-group">
                <button
                    class="form-submit btn ${buttonStyle} font-weight-bold text-uppercase"
                    type="submit"
                >
                    ${buttonText}
                </button>
            </div>
        `;

        html += `</form>`;

        return html;
    },
    update() {
        let id = Helper.makeId();

        let html = '';
        html += Snippet.getHtml(id);

        html += '<scr' + 'ipt>';
        html += Snippet.getDocumentReadyScript(id);
        html += `
            docReady${id}(function () {
                let validationRequest${id} = new ValidationRequest("${id}", 'estimate_search');
                validationRequest${id}.init();
            });
        `;
        html += '</scr' + 'ipt>';

        Snippet.save(html);
        Settings.save();
    },
    save(html) {
        html = html.replace(/ +(?= )/g, '').trim();
        parent.document.querySelector('#hidContentModuleCode').value = html;
    }
}

// Initialise
Settings.restore();
ModalForm.register();
Snippet.update();
