(function() {
    if (typeof (window.getURLParameter) === 'undefined') {
        window.getURLParameter = (name, defaultVal) => {
            return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || defaultVal;
        }
    }

    var fullConfiguration = {
        ai: true,
        apiEndpoint: window.location.protocol + '//' + window.location.hostname + (window.location.port == '' ? '' : ":" + window.location.port) + '/api',
        apiEndpointScheme: "{apiEndpoint}/{apiMethod}",
        apiCredentials: {
            username: "duden",
            password: "duden",
            apiKey: ""
        },
        activated: true,
        configFile: null,
        colors: {
            spellingError: '#faa6ae',
            gramarError: '#abe89e',
            rejectedWord: '#abe89e',
            styleError: '#ffd7a8',
            glossaryInfo: '#ffff00'
        },
        cssFiles: [
            '../../dkce/assets/css/dkce.css',
            './style_test.css'
        ],
        correctionProposals: true,
        debug: false,
        detectManualHyphenation: true,
        dictionaries: [],
        fallbackLanguage: "en",
        glossary: null,
        hideStatusPanel: false,
        hyphenation: null,
        hyphenationStandard: null,
        hyphenationUnaest: null,
        ignoreAttributes: [],
        layerAttributes: [],
        useSingleWordModeOnLayers: true,
        ignoreClasses: [],
        ignoreCharacters: "",
        checkLangauges: [],
        language: window.navigator.language.substring(0, 2),
        markupElement: "span",
        markupMode: 'text',
        maxConcurrentRequests: 0,
        delayBetweenRequestsInMs: 0,
        messageLanguage: null,
        messageLevel: 3,
        openContextMenuOn: "mouseOver",
        orthographyStandard: null,
        overlayMode: getURLParameter('overlayMode') == 'true' ? true : false,
        propertySets: [],
        singleWordModeAttributes: ['duden-use-single-word-mode'],
        singleWordModeClasses: ['duden-use-single-word-mode'],
        proposalDictionary: 'Proposals',
        removeMarkupForSelection: true,
        setUpWatcher: false,
        singleWordMode: false,
        spellcheckingLevel: 3,
        styleColloquial: null,
        styleFiller: null,
        styleForeign: null,
        styleOld: null,
        styleRegional: null,
        styleOffensive: null,
        styleComplexity: null,
        styleGenderInclusive: null,
        textLanguage: null,
        maxCanvasWidth: 512,
        maxCanvasHeight: 512,
        debugCanvas: false,
        zIndex: 20
    };

    var lastError = null;
    function load(key, defaultValue, parse) {
        // NOTE(jochen): dkceConfig settings should be bound to URL path
        if (key == 'dkceConfig') {
            key = window.location.pathname + '.dkceConfig';
        }
        lastError = null;
        try {
            var item = localStorage.getItem(key);
            if (!item) {
                return defaultValue;
            }
            var result = item;
            if (parse) {
                result = JSON.parse(item);
            }
            return result;
        } catch (e) {
            console.log(e);
            lastError = e;
        }
        return defaultValue;
    };

    function save(key, value, stringify) {
        // NOTE(jochen): dkceConfig settings should be bound to URL path
        if (key == 'dkceConfig') {
            key = window.location.pathname + '.dkceConfig';
        }
        lastError = null;
        try {
            if (stringify) {
                value = JSON.stringify(value);
            }
            localStorage.setItem(key, value);
        } catch (e) {
            lastError = e;
        }
    };

    function errMsg(msg) {
        var el = document.getElementById("error");

        if (msg && msg != "") {
            el.innerText = msg;
            el.style.display = 'block';
        } else {
            el.style.display = 'none';
        }
    }

    function initEditor(defaultConfig) {
        defaultConfig = JSON.stringify(defaultConfig, undefined, 4);
        var toggle = document.getElementById("toggle");
        var toggleCheckbox = document.getElementById("collapsible");
        var applyButton = document.getElementById("config.apply");
        var resetButton = document.getElementById("config.reset");
        var fullButton = document.getElementById("config.full");
        var config = document.getElementById("config");

        var initialize = true;

        toggleCheckbox.checked = load("dkceEditorExpanded", false, true);

        toggle.addEventListener("click", function() {
            save("dkceEditorExpanded", !toggleCheckbox.checked, true);
        });

        config.value = load("dkceConfig", defaultConfig, false);
        if (lastError) {
            initialize = false;
            errMsg(lastError);
        }

        try {
            var settings = JSON.parse(config.value);
            for (var key in settings) {
                var uriParameter = getURLParameter(key);
                if(uriParameter) {
                    if (uriParameter === "true") uriParameter = true;
                    if (uriParameter === "false") uriParameter = false;
                    settings[key] = uriParameter;
                }
            }
            config.value = JSON.stringify(settings, undefined, 4);
        } catch {}

        applyButton.addEventListener("click", (ev) => {
            save("dkceConfig", config.value, false);
            save("textAreaHeight", config.style.height);
            location.reload();
        });

        resetButton.addEventListener("click", (ev) => {
            localStorage.removeItem(window.location.pathname + '.dkceConfig');
            config.value = defaultConfig;
            save("textAreaHeight", config.style.height);
            location.reload();
        });

        fullButton.addEventListener("click", (ev) => {
            config.value = JSON.stringify(fullConfiguration, undefined, 4);
            save("dkceConfig", config.value, false);
            save("textAreaHeight", config.style.height);
            location.reload();
        });

        var textAreaHeight = load("textAreaHeight", null);
        if (textAreaHeight) {
            config.style.height = textAreaHeight;
        } else {
            config.setAttribute("style", "height:" + (config.scrollHeight) + "px;overflow-y:hidden;");
        }

        if (initialize) {
            try {
                window.onInitialize(JSON.parse(config.value));
            } catch (e) {
                errMsg(e);
            }
        }
    }

    window.initDKCEConfigEditor = function(defaultConfig) {
        if (defaultConfig && defaultConfig.hasOwnProperty('path')) {
            fullConfiguration.path = defaultConfig.path;
        }

        window.addEventListener("load", function () {
            var req = new XMLHttpRequest();
            req.addEventListener("load", () => {
                if (req.status == 200) {
                    if (req.responseText !== '0') {
                        document.getElementById("configuration-editor").innerHTML = req.responseText;
                        initEditor(defaultConfig);
                    }
                }
            });
            req.open("GET", "../dkceConfig.html.tpl");
            req.send();
        });
    };
})();
