module.exports = function () {
    var getMicrosoftWordData = function (html) {
        var tag = document.createElement("div");
        tag = $(tag);
        tag.html(html);
        var content = tag.html();
        content = content.replace(/<!--[\s\S]+?-->/gi, '');
        content = content.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '');
        content = content.replace(/<(\/?)s>/gi, "<$1strike>");
        content = content.replace(/&nbsp;/gi, ' ');
        content = content.replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function (str, spaces) {
            return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : '';
        });

        tag.html(content);
        turnTags(tag, true);
        $('p', tag).each(function () {
            var str = $(this).attr('style');
            var matches = /mso-list:\w+ \w+([0-9]+)/.exec(str);
            if (matches) {
                $(this).data('_listLevel', parseInt(matches[1], 10));
            }
        });
        var lastLevel = 0;
        var pnt = null;
        $('p', tag).each(function () {
            var curLevel = $(this).data('_listLevel');
            if (curLevel != undefined) {
                var txt = $(this).text();
                var listTag = '<ul></ul>';
                if (/^\s*\w+\./.test(txt)) {
                    var matches = /([0-9])\./.exec(txt);
                    if (matches) {
                        var start = parseInt(matches[1], 10);
                        listTag = start > 1 ? '<ol start="' + start + '"></ol>' : '<ol></ol>';
                    } else {
                        listTag = '<ol></ol>';
                    }
                }

                if (curLevel > lastLevel) {
                    if (lastLevel == 0) {
                        $(this).before(listTag);
                        pnt = $(this).prev();
                    } else {
                        pnt = $(listTag).appendTo(pnt);
                    }
                }
                if (curLevel < lastLevel) {
                    for (var i = 0; i < lastLevel - curLevel; i++) {
                        pnt = pnt.parent();
                    }
                }
                $('span:first', this).remove();
                pnt.append('<li>' + $(this).html() + '</li>');
                $(this).remove();
                lastLevel = curLevel;
            } else {
                lastLevel = 0;
            }
        });
        $('span:empty', tag).remove();
        $('[style]', tag).removeAttr('style');
        $('[align]', tag).removeAttr('align');
        $('[dir]', tag).removeAttr('dir');
        $('span', tag).replaceWith(function () { return $(this).contents(); });
        $('input', tag).remove();
        $('button', tag).remove();
        $('label', tag).remove();
        $('a', tag).remove();
        $("[class^='Mso']", tag).removeAttr('class');
        $('p:empty', tag).remove();
        var outHtml = tag.html().trim().replace(/\u200C/g, ' ').replace(/\&zwnj;/g, ' ');
        return outHtml;
    }
    var getHtmlData = function (html) {
        var tag = document.createElement("div");
        tag = $(tag);
        tag.html(html);
        var content = tag.html();
        content = content.replace(/<!--[\s\S]+?-->/gi, '');
        content = content.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '');
        content = content.replace(/<(\/?)s>/gi, "<$1strike>");
        content = content.replace(/&nbsp;/gi, ' ');
        content = content.replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function (str, spaces) {
            return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : '';
        });
        tag.html(content);
        turnTags(tag, true);

        $('span:empty', tag).remove();
        $('[style]', tag).removeAttr('style');
        $('[align]', tag).removeAttr('align');
        $('[dir]', tag).removeAttr('dir');
        $('[class]', tag).removeAttr('class');
        $('span', tag).replaceWith(function () { return $(this).contents(); });
        $('p:empty', tag).remove();
        $('input', tag).remove();
        $('button', tag).remove();
        $('label', tag).remove();
        $('a', tag).remove();
        $('img', tag).addClass("mimage");
        var outHtml = tag.html().trim().replace(/\u200C/g, ' ').replace(/\&zwnj;/g, ' ');
        return outHtml;
    }
    var turnTags = function (oldTag, first) {
        var tagChildren = $(oldTag).children();
        $.each(tagChildren, function () {
            var tableLines = [];
            var tag = $(this);
            var replaceTag;
            if (tag.length) {
                switch (tag[0].nodeName.toLowerCase()) {
                    case "u":
                        replaceTag = "<span style='text-decoration-line: underline;'>" +
                            tag.text() + "</span>";
                        tag.replaceWith(replaceTag);
                        break;
                    case "i":
                        replaceTag = "<span style='font-style: italic;'>" +
                            tag.text() + "</span>";
                        tag.replaceWith(replaceTag);
                        break;
                    case "p":
                        if (!first) {
                            replaceTag = "<span>" + tag.text() + "</span>";
                            tag.replaceWith(replaceTag);
                        }

                        break;
                    case "b":
                    case "strong":
                        replaceTag = "<span style='font-weight: bold;'>" +
                            tag.text() + "</span>";
                        tag.replaceWith(replaceTag);
                        break;
                    case "img":
                        tag.css({
                            "max-width": "100%",
                            "max-height": "100%"
                        });
                        break;
                    case "table":
                        var trList = tag.find('tbody tr');
                        if (trList.length) {
                            $.each(trList, function () {
                                var tr = $(this);
                                var newTag;
                                if (first)
                                    newTag = "<p>" + tr.text().trim() + "</p>";
                                else
                                    newTag = "<span>" + tr.text().trim() + "</span><br>";
                                tableLines.push(newTag);
                            });
                            tag.replaceWith(tableLines);
                        } else {
                            tag.replaceWith("<span></span>");
                        }
                        break;
                }
                if (tag.children().length)
                    turnTags(tag, false);
            }
        });
    }
    var textToJson = function (pastedInput) {
        let rawRows = pastedInput.split("\n");
        let output = []
        rawRows.forEach((rawRow, idx) => {
            let values = rawRow.split("\t");
            if (values && values.length)
                for (var i = 0; i < values.length; i++) {
                    output.push(trimText(values[i]));
                }
        })
        return output;
    }
    var trimText = function (val) {
        try {
            return val.trim();
        } catch (e) {
            return "";
        }
    }
    return {
        textToJson: textToJson,
        getMicrosoftWordData: getMicrosoftWordData,
        getHtmlData: getHtmlData
    };
}();
