RED.envVar = (function() {
    function saveEnvList(list) {
        const items = list.editableList("items")
        const new_env = [];
        items.each(function (i,el) {
            var data = el.data('data');
            var item;
            if (data.nameField && data.valueField) {
                item = {
                    name: data.nameField.val(),
                    value: data.valueField.typedInput("value"),
                    type: data.valueField.typedInput("type")
                };
                new_env.push(item);
            }
        });
        return new_env;
    }

    function getGlobalConf(create) {
        var gconf = null;
        RED.nodes.eachConfig(function (conf) {
            if (conf.type === "global-config") {
                gconf = conf;
            }
        });
        if ((gconf === null) && create) {
            var cred = {
                _ : {},
                map: {}
            };
            gconf = {
                id: RED.nodes.id(),
                type: "global-config",
                env: [],
                name: "global-config",
                label: "",
                hasUsers: false,
                users: [],
                credentials: cred,
                _def: RED.nodes.getType("global-config"),
            };
            RED.nodes.add(gconf);
        }
        return gconf;
    }

    function applyChanges(list) {
        var gconf = getGlobalConf(false);
        var new_env = [];
        var items = list.editableList('items');
        var credentials = gconf ? gconf.credentials : null;
        if (!gconf && list.editableList('length') === 0) {
            // No existing global-config node and nothing in the list,
            // so no need to do anything more
            return
        }
        if (!credentials) {
            credentials = {
                _ : {},
                map: {}
            };
        }
        items.each(function (i,el) {
            var data = el.data('data');
            if (data.nameField && data.valueField) {
                var item = {
                    name: data.nameField.val(),
                    value: data.valueField.typedInput("value"),
                    type: data.valueField.typedInput("type")
                };
                if (item.name.trim() !== "") {
                    new_env.push(item);
                    if (item.type === "cred") {
                        credentials.map[item.name] = item.value;
                        credentials.map["has_"+item.name] = (item.value !== "");
                        item.value = "__PWRD__";
                    }
                }
            }
        });
        if (gconf === null) {
            gconf = getGlobalConf(true);
        }
        if (!gconf.credentials) {
            gconf.credentials = {
                _ : {},
                map: {}
            };
        }
        if ((JSON.stringify(new_env) !== JSON.stringify(gconf.env)) ||
            (JSON.stringify(credentials) !== JSON.stringify(gconf.credentials))) {
            gconf.env = new_env;
            gconf.credentials = credentials;
            RED.nodes.dirty(true);
        }
    }

    function getSettingsPane() {
        var gconf = getGlobalConf(false);
        var env = gconf ? gconf.env : [];
        var cred = gconf ? gconf.credentials : null;
        if (!cred) {
            cred = {
                _ : {},
                map: {}
            };
        }

        var pane = $("<div/>", {
            id: "red-ui-settings-tab-envvar",
            class: "form-horizontal"
        });
        var content = $("<div/>", {
            class: "form-row node-input-env-container-row"
        }).css({
            "margin": "10px"
        }).appendTo(pane);

        var label = $("<label></label>").css({
            width: "100%"
        }).appendTo(content);
        $("<i/>", {
            class: "fa fa-list"
        }).appendTo(label);
        $("<span/>").text(" "+RED._("env-var.header")).appendTo(label);

        var list = $("<ol/>", {
            id: "node-input-env-container"
        }).appendTo(content);
        var node = {
            type: "",
            env: env,
            credentials: cred.map,
        };
        RED.editor.envVarList.create(list, node);

        var buttons = $("<div/>").css({
            "text-align": "right",
        }).appendTo(content);
        var revertButton = $("<button/>", {
            class: "red-ui-button"
        }).css({
        }).text(RED._("env-var.revert")).appendTo(buttons);

        var items = saveEnvList(list);
        revertButton.on("click", function (ev) {
            list.editableList("empty");
            list.editableList("addItems", items);
        });

        return pane;
    }

    function init(done) {
        RED.userSettings.add({
            id:'envvar',
            title: RED._("env-var.environment"),
            get: getSettingsPane,
            focus: function() {
                var height = $("#red-ui-settings-tab-envvar").parent().height();
                $("#node-input-env-container").editableList("height", (height -100));
            },
            close: function() {
                var list = $("#node-input-env-container");
                try {
                    applyChanges(list);
                }
                catch (e) {
                    console.log(e);
                    console.log(e.stack);
                }
            }
        });

        RED.actions.add("core:show-global-env", function() {
            RED.userSettings.show('envvar');
        });
    }

    return {
        init: init,
    };

})();
