import { __assign, __rest, __spreadArray } from "tslib";
import React, { useMemo, useContext, useEffect, useRef, useState } from "react";
import { Row, Tooltip, Icons, Column, Props, Text, LangContext, Select, MultiSelect, Common, Icon } from "v-eris";
import { Color } from "../../types/types.color";
import { BuildContext } from "../Build/build";
import { AuthContext } from "../../components/Auth/auth";
import "./tools.scss";
export var Tools = function (props) {
    var className = props.className, column = props.column, cycle = props.cycle, simple = props.simple, style = props.style, onChange = props.onChange, value = props.value, list = props.list, rest = __rest(props, ["className", "column", "cycle", "simple", "style", "onChange", "value", "list"]);
    var lang = useContext(LangContext);
    var wrapElem = useRef(null);
    var build = useContext(BuildContext);
    var auth = useContext(AuthContext);
    var _a = useState({}), state = _a[0], setState = _a[1];
    var settings = build.settings;
    if (!list)
        list = [];
    var elemsWidthChildren = [];
    var standAlone = onChange ? false : true;
    var mapApiState = standAlone ? state : value;
    var getToolValue = function (key) {
        if (standAlone) {
            var needle = list.find(function (f) { return f.key == key; });
            if (needle && needle.children)
                return true;
            return mapApiState[key];
        }
        ;
        return mapApiState[key];
    };
    var setToolValue = function (data, type) {
        if (standAlone) {
            mapApiState[data.key] = data.value;
            return;
        }
        ;
        onChange({ type: type || data.type, key: data.key, value: data.value });
    };
    var setSettings = function (settingsSource) {
        setToolValue({ key: settingsSource }, "settings");
    };
    var clickout = function () {
        for (var _i = 0, elemsWidthChildren_1 = elemsWidthChildren; _i < elemsWidthChildren_1.length; _i++) {
            var item = elemsWidthChildren_1[_i];
            if (!getToolValue(item.key))
                continue;
            var data = __assign(__assign({}, item), { value: !getToolValue(item.key) });
            setToolValue(data);
        }
        ;
    };
    useEffect(function () {
        var fn = function (event) {
            if (!wrapElem.current)
                return;
            var inside = wrapElem.current.contains(event.target);
            if (inside)
                return;
            clickout();
        };
        document.addEventListener("mousedown", fn);
        return function () {
            document.removeEventListener("mousedown", fn);
        };
    }, [mapApiState, lang.current]);
    var makeEvent = function (e, item, depth, forceValue) {
        if (e.defaultPrevented)
            return;
        if (!depth)
            clickout();
        var key = item.redirect ? item.redirect : item.key;
        var v = settings.keyExist(item.key) ? settings.getSecureValue(key) : getToolValue(key);
        var value = (item.type == "toggle" || item.type == "selector") ? !v : v;
        if (forceValue !== undefined)
            value = forceValue;
        var event = {
            event: e,
            target: item,
            value: value,
            redirect: item.redirect,
            feedback: null,
            preventDefault: function () {
                this.defaultPrevented = true;
            },
            defaultPrevented: false
        };
        if (event.defaultPrevented)
            return;
        var data = __assign(__assign({}, item), { value: event.value });
        data.key = key;
        if (settings.keyExist(key)) {
            if (auth.access < 5) {
                settings.change(key, data.value);
            }
            else {
                settings.setValueAsync(key, data.value, true);
            }
            ;
        }
        else
            setToolValue(data);
    };
    var makeTool = function (item, index, depth) {
        var children = item.children && Array.isArray(item.children) && item.children.length ? [] : null;
        var visibleElements = 0;
        if (children) {
            elemsWidthChildren.push(item);
            var n = 0;
            for (var _i = 0, _a = item.children; _i < _a.length; _i++) {
                var child = _a[_i];
                var temp = makeTool(child, n, depth + 1);
                visibleElements += temp.hidden ? 0 : 1;
                children === null || children === void 0 ? void 0 : children.push(temp.elem);
                n++;
            }
            ;
        }
        ;
        var value = null;
        var secureRef = settings.getSecureValue(item.secure);
        var secureValue = settings.getSecureValue(item.key);
        var secureTable = secureValue && secureValue.table ? __assign({}, secureValue.table) : {};
        var systemData = settings.getSystemData(item.key);
        var inheritedTitle = "";
        var params = false;
        var inheritedDesc = settings.getDesc(item.key);
        var settingsVisibility = settings.getSecureValue(item.settingsVisibility) ? true : false;
        var subVisibility = settings.getSecureValue(item.subVisibility);
        var visibilityKey = settings.keyExist(item.visibilityKey) ? settings.getSecureValue(item.visibilityKey) : true;
        var itemVisible = settings.keyExist(item.visibility) ? settings.getSecureValue(item.visibility) : true;
        var extra = item.extra || {};
        var itemHidden = itemVisible !== true;
        var disabled = item.disabled;
        var icon = item.icon || (systemData ? systemData.icon : null);
        var offParam = "";
        if (!systemData) {
            inheritedTitle = settings.keyExist(item.key) ? settings.getTitle(item.key) : lang.get(item.key);
        }
        else if (extra.query) {
            inheritedTitle = systemData.button || settings.getTitle(item.key);
            params = __spreadArray([], secureValue.list, true);
            secureValue = { list: [] };
            for (var _b = 0, params_1 = params; _b < params_1.length; _b++) {
                var item_1 = params_1[_b];
                if (!secureTable[item_1.token] || !secureTable[item_1.token].Active)
                    continue;
                secureValue.list.push(item_1.token);
            }
            ;
        }
        else {
            inheritedTitle = systemData.button || settings.getTitle(item.key);
            params = systemData.params && Array.isArray(systemData.params) ? __spreadArray([], systemData.params, true) : false;
            var secureArray_1 = settings.getSecureValue(systemData.secure);
            if (params && secureArray_1 && Array.isArray(secureArray_1.list)) {
                params = params.filter(function (f) { return secureArray_1.list.indexOf(f.value) > -1; });
            }
            ;
            if (params) {
                var f = params.findIndex(function (f) { return f.defaultIgnored; });
                if (f > -1)
                    offParam = params[f].value;
            }
            ;
        }
        ;
        if (!itemHidden && visibilityKey && Array.isArray(visibilityKey.list) && item.visibilityValue) {
            if (visibilityKey.list.indexOf(item.visibilityValue) < 0)
                itemHidden = true;
            else
                itemHidden = false;
        }
        ;
        if (Array.isArray(params) && !params.length)
            itemHidden = true;
        if (children && !visibleElements)
            itemHidden = true;
        if (item.type == "display") {
            value = settings.keyExist(item.key) ? secureValue : getToolValue(item.key);
        }
        else if (item.type == "newline") {
            return {
                hidden: itemHidden,
                elem: (React.createElement("div", { className: "tools-module-newline" + (itemHidden ? " hidden" : ""), key: item.key || index }))
            };
        }
        else if (extra.query) {
            value = (React.createElement("div", { className: (depth > 0 ? "column" : "row") },
                React.createElement(MultiSelect, { value: secureValue ? (secureValue.list || secureValue) : [], headerless: true, stretch: true, style: { display: subVisibility === false ? "none" : null }, className: (params || []).length < 2 ? "hidden" : "", onChange: function (event) {
                        var v = __assign({}, secureTable);
                        for (var _i = 0, params_2 = params; _i < params_2.length; _i++) {
                            var item_2 = params_2[_i];
                            v[item_2.token].Active = false;
                        }
                        ;
                        for (var _a = 0, _b = event.value; _a < _b.length; _a++) {
                            var token = _b[_a];
                            v[token].Active = true;
                        }
                        ;
                        makeEvent({}, item, depth, v);
                    }, suggestions: (params || []).map(function (item) {
                        return {
                            tooltip: item.name,
                            value: item.token,
                            icon: (React.createElement(Icon, { style: { fontFamily: "Roboto" } },
                                React.createElement(Color, { simple: true, value: (((secureRef || {}).table || {})[item.token] || {}).MarksColor }),
                                Common.paddingLeft(item.sac, 3, "0") + ":" + Common.paddingLeft(item.sic, 3, "0"))),
                        };
                    }) })));
        }
        else if (item.type == "list") {
            value = (React.createElement("div", { className: (depth > 0 ? "column" : "row") },
                React.createElement(Row, { className: "tools-module-text tools-module-clickable" + (depth > 0 && ((systemData && systemData.button) || item.button) ? "" : " hidden"), key: item.key || index, onClick: function () {
                        if (!secureRef)
                            return;
                        makeEvent({}, item, depth, __assign(__assign({}, secureValue), { list: secureValue && secureValue.list && !secureValue.list.length ? [secureRef.defaultValue] : [] }));
                    } },
                    icon,
                    React.createElement(Text, null,
                        lang.get(inheritedTitle),
                        React.createElement("span", { className: Props.className("tools-module-line-settings", { hidden: !item.settings || !settingsVisibility }), onClick: function (e) { e.stopPropagation(); setSettings(item.settings); } },
                            React.createElement(Icons.cog, null)))),
                React.createElement(MultiSelect, __assign({ value: secureValue ? (secureValue.list || secureValue) : [], headerless: true, stretch: true, style: { display: subVisibility === false ? "none" : null }, className: (params || []).length < 2 ? "hidden" : "" }, extra, { onChange: function (v) { return makeEvent({}, item, depth, { list: v.value, sort: v.sort, defaultValue: v.defaultValue }); }, suggestions: (Array.isArray(params) ? params : []).map(function (child) {
                        return {
                            tooltip: !simple && child.icon ? lang.get(child.title) : null,
                            title: simple ? (lang.get(child.prefix) || lang.get(child.title)) : lang.get(child.title),
                            value: child.value,
                            icon: child.icon
                        };
                    }) }))));
        }
        else if (item.type == "slider") {
            value = (React.createElement("div", { className: (depth > 0 ? "column" : "row") },
                React.createElement(Row, { className: "tools-module-text tools-module-clickable" + (depth > 0 && ((systemData && systemData.button) || item.button) ? "" : " hidden"), key: item.key || index, onClick: function () {
                        if (!secureRef || !secureRef.defaultValue || !offParam)
                            return;
                        makeEvent({}, item, depth, secureValue == offParam ? secureRef.defaultValue : offParam);
                    } },
                    icon,
                    React.createElement(Text, null,
                        lang.get(inheritedTitle),
                        React.createElement("span", { className: Props.className("tools-module-line-settings", { hidden: !item.settings || !settingsVisibility }), onClick: function (e) { e.stopPropagation(); setSettings(item.settings); } },
                            React.createElement(Icons.cog, null)))),
                React.createElement(Select, __assign({ icon: icon, cycle: cycle, stretch: depth > 0, headerless: depth > 0, row: depth > 0, minWidth: depth > 0 ? undefined : "20px", value: secureValue, style: { display: subVisibility === false ? "none" : null }, className: (params || []).length < 2 ? "hidden" : "" }, extra, { onSelect: function (v) { return makeEvent({}, item, depth, v.value); }, list: (Array.isArray(params) ? params : []).map(function (child) {
                        return { title: simple ? (lang.get(child.prefix) || lang.get(child.title)) : lang.get(child.title), value: child.value, icon: child.icon };
                    }) }))));
        }
        else if (item.type == "buttons") {
            value = (React.createElement(Row, { className: "tools-module-text tools-module-buttons", key: item.key || index },
                icon,
                React.createElement(Text, null,
                    lang.get(inheritedTitle),
                    React.createElement("span", { className: Props.className("tools-module-line-settings", { hidden: !item.settings || !settingsVisibility }), onClick: function (e) { e.stopPropagation(); setSettings(item.settings); } },
                        React.createElement(Icons.cog, null)))));
        }
        else if (item.type == "settings") {
            value = (React.createElement(Row, { className: "tools-module-line-simple", key: item.key || index },
                React.createElement("span", { onClick: function (e) { e.stopPropagation(); setSettings(item.settings); } }, icon)));
        }
        else if (item.type == "selector") {
            value = (React.createElement(Row, { className: "tools-module-line", key: item.key || index }, (React.createElement(React.Fragment, null,
                icon,
                React.createElement(Text, null, ((settings.keyExist(item.link) ? settings.getSecureValue(item.link) : getToolValue(item.link)) || "") + (item.appendix || ""))))));
        }
        else {
            value = (React.createElement(Row, { className: "tools-module-line" + (simple && depth < 1 ? " tools-module-line-simple" : ""), key: item.key || index },
                icon,
                React.createElement(Text, null,
                    lang.get(inheritedTitle),
                    React.createElement("span", { className: Props.className("tools-module-line-settings", { hidden: !item.settings || !settingsVisibility }), onClick: function (e) { e.stopPropagation(); setSettings(item.settings); } },
                        React.createElement(Icons.cog, null)))));
        }
        ;
        var hidden = depth > 0 ? (!lang.get(inheritedDesc)) : (!lang.get(inheritedTitle));
        var active = false;
        if ((item.type == "slider" || item.type == "toggle") && offParam) {
            active = secureValue != offParam;
        }
        else if (item.type == "list") {
            active = secureValue && secureValue.list && secureValue.list.length;
        }
        else {
            active = (item.type == "toggle") && (settings.keyExist(item.key) ? secureValue : getToolValue(item.key));
        }
        ;
        return { hidden: itemHidden, elem: (React.createElement("div", { className: Props.className("tools-module-item", {
                    hidden: itemHidden,
                    display: item.type == "display",
                    disabled: disabled,
                    extraPadding: item.extraPadding,
                    selector: item.type == "selector",
                    active: active
                }), key: (item.key || index) + ":" + item.secure, onClick: function (e) {
                    if (depth < 1 && secureRef && secureRef.defaultValue && offParam) {
                        makeEvent({}, item, depth, secureValue == offParam ? secureRef.defaultValue : offParam);
                        return;
                    }
                    ;
                    if (item.type != "toggle")
                        return;
                    makeEvent(e, item, depth);
                } },
                React.createElement(Tooltip, { content: depth > 0 ? lang.get(inheritedDesc) : lang.get(inheritedTitle), key: (item.key || index) + ":" + item.secure, free: depth > 0 ? false : true, style: {
                        opacity: hidden ? "0" : null,
                        pointerEvents: hidden ? "none" : null,
                    } }, value),
                React.createElement("div", { className: Props.className("tools-module-children", {
                        active: children && (settings.keyExist(item.key) ? secureValue : getToolValue(item.key))
                    }), onClick: function (e) {
                        e.preventDefault();
                    } }, children))) };
    };
    var elements = useMemo(function () {
        var length = 0;
        var p = list.map(function (item, index) {
            var temp = makeTool(item, index, 0);
            length += temp.hidden ? 0 : 1;
            return temp.elem;
        });
        return { length: length, list: p };
    }, [mapApiState, lang.current, settings.it]);
    return (React.createElement("div", { className: Props.className("tools-module", { hidden: elements.length < 1, simple: simple }), ref: wrapElem, style: style }, column ? (React.createElement(Column, { gap: simple ? 5 : 14 }, elements.list)) : (React.createElement(Row, { gap: simple ? 5 : 14 }, elements.list))));
};
//# sourceMappingURL=tools.js.map