import React, { useState, useEffect, useMemo, useContext, useRef } from "react";
import { Card, List, Icons, LangContext, Common, Row, Button, Column, Select, Space, Props, Tooltip, Toggle } from "v-eris";
import { ContentMenu } from "../../placeholders/ContentMenu/content.menu";
import { ContentContainer } from "../../placeholders/ContentContainer/content.container";
import { SettingsParamToKey, SettingsParamToKey3, useSettings } from "../../utility/use.settings";
import { BuildContext } from "../../components/Build/build";
export var SettingsRoute = function () {
    var lang = useContext(LangContext);
    var qsRef = useRef({});
    var isSelf = useRef(false);
    var _a = useState(false), altered = _a[0], setAltered = _a[1];
    var build = useContext(BuildContext);
    var route = build.routes["settings"];
    var qs = build.query;
    var alterListener = function (e) {
        if (e.key != "Control")
            return;
        e.preventDefault();
        setAltered(e.type == "keydown" ? true : false);
    };
    useEffect(function () {
        document.addEventListener("keydown", alterListener);
        document.addEventListener("keyup", alterListener);
        return function () {
            document.removeEventListener("keydown", alterListener);
            document.removeEventListener("keyup", alterListener);
        };
    }, []);
    qs.section = Common.string(qs.section || "");
    qs.item = Common.string(qs.item || "");
    qs.type = Common.string(qs.type || "");
    qs.token = Common.string(qs.token || "");
    if (!route.sections[Common.string(qs.section)])
        qs.section = route.list[0] ? route.list[0].key : "";
    var section = qs.section;
    var sectionItem = route.sections[section] || {};
    var sectionTable = route.table[qs.item];
    if (sectionTable && isSelf.current) {
        var length_1 = 0;
        for (var _i = 0, sectionTable_1 = sectionTable; _i < sectionTable_1.length; _i++) {
            var item = sectionTable_1[_i];
            var keySection = SettingsParamToKey3(qs.item, item.key);
            var visibleSection = build.settings.getExclusionValue(keySection);
            if (!visibleSection)
                continue;
            length_1++;
        }
        ;
        if (!length_1)
            sectionTable = null;
    }
    ;
    if (!sectionTable) {
        qs.item = sectionItem.list && sectionItem.list[0] ? sectionItem.list[0].key : "";
        sectionTable = route.table[qs.item] || [];
    }
    ;
    qsRef.current = qs;
    var settingsInheritance = useSettings({
        token: qs.token || "users:self",
        table: build.settingsTable,
        connectionless: true,
    });
    var preparedTypes = useMemo(function () {
        var array = [];
        var icons = {
            "configurations": React.createElement(Icons.key, null),
            "roles": React.createElement(Icons.users, null),
            "users": React.createElement(Icons.user, null),
        };
        for (var _i = 0, _a = settingsInheritance.inheritanceStack; _i < _a.length; _i++) {
            var stack = _a[_i];
            array.push({
                token: stack.type + ":" + stack.token,
                k: stack.token,
                name: stack.name,
                icon: icons[stack.type]
            });
        }
        ;
        if (settingsInheritance.inheritanceStack.length)
            isSelf.current = !qs.token || qs.token == "self" ? true : settingsInheritance.isSelf();
        if (isSelf.current)
            array = array.length > 0 ? [array[array.length - 1]] : [];
        return array;
    }, [settingsInheritance.iteration, build.settings.iteration]);
    var typeNeedle = preparedTypes.find(function (f) { return f.token == qs.type; });
    var type = typeNeedle ? typeNeedle.token : (preparedTypes.length ? preparedTypes[preparedTypes.length - 1].token : "");
    var settings = useSettings({
        token: isSelf.current ? "users:self" : type,
        table: build.settingsTable,
        connectionless: true,
        replicate: isSelf.current ? [build.settings] : null
    });
    var contentList = useMemo(function () {
        return sectionTable.map(function (item) {
            var keySection = SettingsParamToKey3(qs.item, item.key);
            var overrideSection = settings.getExclusionOverride(keySection);
            var visibleSection = settings.getExclusionValue(keySection);
            //console.log( keySection, visibleSection, settings );
            return (React.createElement(Card, { className: "eris-line" + (isSelf.current && !visibleSection ? " hidden" : ""), key: item.key, header: React.createElement("div", null,
                    item.icon,
                    React.createElement(Space, null),
                    lang.get(item.title),
                    React.createElement("span", { className: "eris-line-toggle" + (isSelf.current ? " hidden" : "") },
                        React.createElement("span", { className: Props.className("eris-parameter-changed", { active: settings.isExclusionChanged(keySection) }) }),
                        React.createElement("span", { className: Props.className("eris-parameter-revert", { active: settings.isExclusionChanged(keySection) }), onClick: function () {
                                settings.revertExclusion(keySection);
                            } }, lang.get("Settings::Revert")),
                        React.createElement(Space, null),
                        React.createElement(Icons.redo, { transition: true, className: Props.className("eris-parameter-clear", {
                                active: !settings.isExclusionCleared(keySection) && settings.isExclusionOverride(keySection) && overrideSection.length > 1
                            }), onClick: function () { return settings.clearExclusionOverride(keySection); } }),
                        React.createElement(Space, null),
                        React.createElement(Tooltip, { content: overrideSection.map(function (item) {
                                return React.createElement("div", { key: item.token },
                                    React.createElement("span", null,
                                        lang.get(item.name),
                                        " "),
                                    item.token == "default" ? lang.get("Settings::HasValue") : lang.get("Settings::OverrideValueSimple"),
                                    React.createElement(Toggle, { value: item.value }));
                            }) },
                            React.createElement(Toggle, { value: visibleSection, onChange: function (e) {
                                    settings.changeExclusion(keySection, e.value);
                                } })))) }, item.list.map(function (parameter) {
                var key = SettingsParamToKey(qs.item, item.key, parameter.key);
                var override = settings.getOverride(key);
                var stringify = "";
                try {
                    stringify = JSON.stringify(settings.getSecureValue(key), null, " ");
                }
                catch (e) {
                    stringify = "";
                }
                ;
                if (parameter.bindless)
                    return null;
                return React.createElement(Card, { key: key, header: React.createElement("div", null,
                        lang.get(parameter.title),
                        React.createElement("span", { className: Props.className("eris-parameter-changed", { active: settings.isChanged(key) }) }),
                        React.createElement("span", { className: Props.className("eris-parameter-revert", { active: settings.isChanged(key) }), onClick: function () {
                                settings.revert(key);
                            } }, lang.get("Settings::Revert")),
                        React.createElement(Tooltip, { content: override.map(function (item) {
                                return React.createElement("div", { key: key + ":" + item.name },
                                    React.createElement("span", null,
                                        lang.get(item.name),
                                        " "),
                                    item.token == "default" ? lang.get("Settings::HasValue") : lang.get("Settings::OverrideValueSimple"),
                                    React.createElement("div", null, React.cloneElement(build.types[item.type], {
                                        value: item.valueSecure,
                                        k: key,
                                        params: item.params,
                                        lang: lang,
                                        stack: item.stack,
                                        extra: parameter.extra,
                                        secure: parameter.secure,
                                        settings: settings
                                    })));
                            }) },
                            React.createElement("span", { className: Props.className("eris-parameter-override", {}) }, settings.isInherit(key) ?
                                lang.get("Settings::InheritFrom", [(settings.isCleared(key) && override.length > 1 ? override[override.length - 2].name : override[override.length - 1].name)])
                                :
                                    (settings.isOverride(key) && override.length > 1 ? lang.get("Settings::IsOverriding", [override[override.length - 2].name]) : ""))),
                        React.createElement(Space, null),
                        React.createElement(Tooltip, { content: lang.get("Settings::ClearOverride") },
                            React.createElement(Icons.redo, { transition: true, className: Props.className("eris-parameter-clear", {
                                    active: !settings.isCleared(key) && settings.isOverride(key) && override.length > 1
                                }), onClick: function () { return settings.clearOverride(key); } })),
                        React.createElement(Space, null),
                        React.createElement("span", { className: altered ? "" : "hidden" }, key + " " + stringify)) }, React.createElement(Column, { className: Props.className("eris-parameter", { booltype: parameter.type == "bool" }) },
                    React.createElement(Row, null, lang.get(parameter.desc)),
                    React.createElement(Row, null,
                        React.cloneElement(build.types[parameter.type], {
                            params: parameter.params,
                            k: key,
                            value: settings.getSecureValue(key),
                            lang: lang,
                            icon: parameter.icon,
                            stack: parameter.stack,
                            extra: parameter.extra,
                            secure: parameter.secure,
                            settings: settings,
                            onChange: function (e, keyIndex) {
                                settings.change(key, e.value, keyIndex);
                            }
                        }),
                        React.createElement("span", null,
                            React.createElement(Space, null),
                            settings.autoCorrected(key) ? lang.get("Settings::AutoCorrected", [settings.autoCorrected(key)]) : null))));
            })));
        });
    }, [qs.section, qs.item, settings.iteration, altered, lang.current]);
    var isLive = false;
    var liveContent = useMemo(function () {
        if (!isLive)
            return null;
        return React.cloneElement(React.createElement("div", null), {
            settings: settings
        });
    }, [isLive, settings.iteration]);
    var treeList = useMemo(function () {
        return route.list.map(function (item) {
            if (!item.list)
                return;
            var length = 0;
            return (React.createElement(List.Item, { icon: item.icon, key: item.key, title: lang.get(item.title) }, item.list.map(function (data) {
                var sectionTable = route.table[data.key];
                if (!sectionTable)
                    return;
                length = 0;
                for (var _i = 0, sectionTable_2 = sectionTable; _i < sectionTable_2.length; _i++) {
                    var item_1 = sectionTable_2[_i];
                    var keySection = SettingsParamToKey3(data.key, item_1.key);
                    var visibleSection = settings.getExclusionValue(keySection);
                    if (!visibleSection)
                        continue;
                    length++;
                }
                ;
                if (!length && isSelf.current)
                    return null;
                return React.createElement(List.Item, { icon: data.icon, title: lang.get(data.title), key: data.key, value: build.buildQuery({ section: item.key, item: data.key }) }, "");
            })));
        });
    }, [route.table, route.list, build.currentLang, settings.iteration]);
    return (React.createElement("div", { className: "eris-content eris-content-selector" },
        React.createElement(ContentMenu, null,
            React.createElement(List, { value: build.buildQuery({ section: qs.section, item: qs.item }), onChange: function (event) {
                    build.setQueryString(event.value);
                }, padding: [3, 6, 3, 8] }, treeList)),
        React.createElement(ContentContainer, null,
            React.createElement("div", { className: "eris-content-header" },
                React.createElement("span", null,
                    React.createElement(Button, { onClick: function () {
                            if (isSelf.current) {
                                build.setQueryString("/");
                                return;
                            }
                            ;
                            var temp = Common.string(qs.token);
                            var split = temp.split(":");
                            var route = split[0];
                            route = String(route).charAt(0).toUpperCase() + String(route).slice(1);
                            var token = split[1];
                            var string = "/admin?section=" + route;
                            if (qs.filter)
                                string += "&filter=" + qs.filter;
                            build.setQueryString(string);
                        } }, "Back"),
                    React.createElement(Space, null),
                    React.createElement(Space, null),
                    React.createElement(Space, null),
                    React.createElement(Space, null),
                    React.createElement(Space, null),
                    React.createElement(Select, { className: isSelf.current ? "hidden" : "", stretch: true, headerless: true, row: true, style: { maxWidth: 400 }, value: type, list: (preparedTypes).map(function (item) {
                            return { icon: item.icon, value: item.token, title: item.name };
                        }), onChange: function (e) {
                            build.setQuery({ type: e.value });
                        } })),
                React.createElement("div", { style: { float: "right" } },
                    React.createElement(Button, { className: (qs.type == "user" && !self ? "" : " hidden"), onClick: function () {
                            //						let needle = storage.list.find(( f ) => f.token == storage.getToken() );
                            //
                            //						if( !needle )
                            //							return;
                            //						window.localStorage.setItem( "RoleMirror", needle.token );
                            //						window.localStorage.setItem( "RoleMirrorName", needle.title );
                        } }, lang.get("Settings::Mirror")),
                    React.createElement(Space, null),
                    React.createElement(Button, { onClick: function () {
                            settings.save();
                        } }, lang.get("Settings::Save")))),
            React.createElement("div", { className: "eris-content-wrap" }, isLive ?
                (React.createElement("div", { className: "eris-content-live" },
                    React.createElement("div", { className: "eris-content-live-params" }, contentList),
                    React.createElement("div", { className: "eris-content-live-result" }, liveContent)))
                :
                    contentList))));
    return React.createElement("div", null);
};
//# sourceMappingURL=settings.route.js.map