var pluginUrl = document.location.toString().replace(/\/[^/]*$/, '/script/tinymce-4.9.4/plugins/faq');
var mode = 'create';

tinymce.PluginManager.add('faq', function (editor, url) {
    editor.addButton('faq', {
        text: 'FAQ',
        icon: false,
        onpostrender: updateOnSelect,
        onclick: showDialog
    });

    function showDialog() {
        var win, contentEditor = {
            output: null, faqs: []
        };

        if (mode = 'update') {
            var thisNode = editor.selection.getNode();
            var thisFAQBox = $(thisNode).parents('.mega-faq');

            let faqs = [];
            var singleFaqs = thisFAQBox.find('.single-faq');
            singleFaqs.each(function (index, element) {

                let question = '';
                $(element).find('._q').each(function (index, q) {
                    question += $(q).html();
                });

                let answer = '';
                $(element).find('._a').each(function (index, a) {
                    answer += $(a).html();
                }) 

                faqs.push({
                    q: question, a: answer
                });

                // console.log(faqs);
            })

            contentEditor.faqs = faqs;
        }

        win = editor.windowManager.open({
            title: "Mega FAQ",
            spacing: 10,
            padding: 10,
            width: 525,
            height: 500,
            url: pluginUrl + '/dialog.html',
            buttons: [
                {
                    text: "Save FAQ", onclick: function () {
                        if (contentEditor.output.length) {
                            var faqsDom = $("<div class=\"mega-faq\"></div>");
                            contentEditor.output.forEach(faq => {
                                var singleFaqDom = $('<div class="single-faq"></div>');
                                singleFaqDom.append('<div class="_q">' + faq.q + '</div>');
                                singleFaqDom.append('<div class="_a">' + faq.a + '</div>');

                                faqsDom.append(singleFaqDom);
                            });

                            if (mode = 'update') {

                                if (!thisFAQBox) {
                                    let thisNode = editor.selection.getNode();
                                    var thisFAQBox = $(thisNode).parents('.mega-faq');
                                }

                                thisFAQBox.remove();
                            }

                            editor.execCommand('mceInsertContent',
                                false, faqsDom[0].outerHTML);
                        }

                        win.close();
                    }
                },
                {
                    text: "Cancel", onclick: function () {
                        win.close();
                    }
                }
            ]
        },
            contentEditor
        );
    }

    function updateOnSelect() {
        var btn = this;
        editor.on('NodeChange', function (e) {
            var node = editor.selection.getNode();
            var instanceDoc = editor.getDoc();
            var container = instanceDoc.getElementsByClassName('mega-faq');

            var descendant = isDescendant(container, node);
            btn.active(descendant);
            if (descendant) {
                mode = 'update';
            } else {
                mode = 'create';
            }
        });
    }

    function isDescendant(parent, child) {
        var node = child;
        while (node != null) {

            for (let index = 0; index < parent.length; index++) {
                var nodeOfParent = parent[index];
                if (node == nodeOfParent) {
                    return true;
                }
            }

            node = node.parentNode;
        }
        return false;
    }

    return {
        getMetadata: function () {
            return {
                name: "Mega FAQ Schema",
                url: "http://bta.com"
            };
        }
    };
});