/* global Extraction */

Extraction.CodeMirror = {};

Extraction.CodeMirror.init = function () {
    document.querySelectorAll("figure[data-type]").forEach(function (element) {
        let options = _getOptions(element.dataset.type);
        if (options) {
            let preChild = _getFirstChild(element, "pre");
            if (preChild) {
                _codeMirror(preChild, options);
            }
        }
    });
    
    
    function _codeMirror(element, options) {
        let codeChild = _getFirstChild(element, "code");
        let raw = (codeChild)?_toRawText(codeChild): _toRawText(element);
        let newDiv = document.createElement("div");
        element.insertAdjacentElement('beforebegin', newDiv);
        let codeMirrorOptions = Object.assign({
            value: raw,
            theme: 'bdf',
            lineNumbers: true,
            readOnly: true,
            tabindex: -1,
            minHeight: 20
        }, options);
        CodeMirror(newDiv, codeMirrorOptions);
        element.remove();
    }
    
    function _toRawText(element) {
        var text = "";
        for (let i = 0; i < element.childNodes.length; ++i) {
            let item = element.childNodes[i];
            switch(item.nodeType) {
                case 3:
                    text += item.textContent;
                    break;
                case 1:
                    if (item.tagName.toLowerCase() === "br") {
                        text += "\n";
                    } else {
                        text += item.innerText;
                    }
                    break;
            }
        }
        return text;
    }
    
    function _getOptions(type) {
        let mode = __checkAlias(type);
        switch(mode) {
            case "ficheblock":
                return {
                    mode: "ficheblock",
                    lineNumbers: false,
                    lineWrapping: true
                };
            case "htmlmixed":
                return {
                    mode: "htmlmixed",
                    lineWrapping: true
                };
            default:
                return {
                    mode: mode
                };
        }
        
        function __checkAlias(type) {
            switch(type) {
                case "ini":
                    return "properties";
                case "java":
                    return "text/x-java";
                case "js":
                    return "javascript";
                case "html":
                    return "htmlmixed";
                default:
                    return type;
            }
        }
       
    }   
    
    
    function _getFirstChild(element, tagName) {
        for(let i = 0; i < element.children.length; i++) {
            let child = element.children[i];
            if (child.tagName.toLowerCase() === tagName) {
               return child;
            }
        }
        return null;
    }
};

$(function() {
    Extraction.CodeMirror.init();
});
