"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FormItem = void 0;
const react_1 = __importStar(require("react"));
const inlines_1 = require("inlines");
const Label_1 = require("./Label");
const __1 = require("../..");
const ObjectItem_1 = require("../ObjectItem");
const icons_1 = require("../../../icons");
// | 'record'
// | 'text'
// | 'cardinality'
const FormItemInner = ({ item: { props, type, field, label, description, validation, options, default: defaultValue, multiple, meta, items, addMultipleLabel = 'Add', properties, }, autoFocus, fieldWidth, value, onChange, item, onChangeObj, width, objValues, hasChanges, valuesChanged, setChanges, alwaysAccept, noLabel, }) => {
    if ((defaultValue && value === undefined) || value === '') {
        value = defaultValue;
    }
    if (multiple && !value && !defaultValue) {
        value = [''];
    }
    if (multiple || type === 'array' || type === 'set' || type === 'references') {
        return (react_1.default.createElement(Label_1.Label, null,
            react_1.default.createElement(__1.List, { item: item, items: items, onChangeObj: onChangeObj, onChange: onChange, field: field, label: label, type: type, value: value, hasChanges: hasChanges, valuesChanged: valuesChanged, setChanges: setChanges, alwaysAccept: alwaysAccept })));
    }
    if (item.type === 'object') {
        const parsedObjArray = [];
        if (properties) {
            for (const i in properties) {
                parsedObjArray.push({ ...properties[i], field: field + '.' + i });
            }
        }
        const objectArray = [
            ...new Set(parsedObjArray
                .map((item) => item.field.split('.')[0])
                .filter((e, i, a) => a.indexOf(e) !== i)),
        ];
        return (react_1.default.createElement(ObjectItem_1.ObjectItem, { key: objectArray[0], d: objectArray[0], autoFocus: autoFocus, onChange: onChangeObj, labelWidth: width, fieldWidth: fieldWidth, onChangeField: onChange, style: {
                width: '100%',
            }, values: objValues, hasChanges: hasChanges, valuesChanged: valuesChanged, setChanges: setChanges, alwaysAccept: alwaysAccept, parsedObjArray: parsedObjArray, field: field }));
    }
    if (item.type === 'type') {
        return '';
    }
    if (item.type === 'references') {
        console.log('tpye', type);
        return 'references';
    }
    if (typeof type === 'function') {
        return (react_1.default.createElement(react_1.default.Fragment, null, react_1.default.createElement(type, {
            // @ts-ignore
            value,
            onChange,
            autoFocus,
            type,
            field,
            label,
            description,
            validation,
            options,
            defaultValue,
            multiple,
            ...props,
        })));
    }
    if (options) {
        return (react_1.default.createElement(__1.Input, { type: "select", value: value, autoFocus: autoFocus, onChange: (v) => {
                onChange(field, v);
            }, options: options.map((value, i) => {
                if (typeof value !== 'object') {
                    return { value: String(i), label: value };
                }
                return value;
            }), ...props, 
            // @ts-ignore
            style: props?.style }));
    }
    if (type === 'json') {
        // console.log('------_>",', JSON.parse(value))
        return (react_1.default.createElement(inlines_1.styled.div, { style: { width: '100%', marginBottom: 16 } }, meta?.format === 'rich-text' ? (
        // @ts-ignore
        react_1.default.createElement(__1.Input, { defaultValue: value ?? '', type: 'rich-text', onChange: ({ json, html }) => {
                onChange(field, json);
                if (meta.linkedField) {
                    onChange(meta.linkedField, html);
                }
            }, ...props })) : (react_1.default.createElement(__1.Code, { onChange: (v) => onChange(field, v), value: value, language: "json" })))
        // </Label>
        );
    }
    if (type === 'boolean') {
        return (react_1.default.createElement(__1.Toggle, { defaultValue: true, label: label, value: value, onChange: (v) => onChange(field, v), 
            // {...props}
            // @ts-ignore
            style: props?.style }));
    }
    if (type === 'range') {
        return (react_1.default.createElement(__1.Row, { style: { width: '100%' } },
            react_1.default.createElement(__1.Input, { onChange: (v) => {
                    onChange(field, {
                        min: v,
                        max: v > value?.max ? v : value?.max ?? v,
                    });
                }, autoFocus: autoFocus, value: value?.min, type: "number", placeholder: "Min", ...props, 
                // @ts-ignore
                style: Object.assign({ marginRight: 16, width: fieldWidth / 2 }, props?.style) }),
            react_1.default.createElement(__1.Input, { onChange: (v) => {
                    onChange(field, {
                        max: v,
                        min: v < value?.min ? v : value?.min ?? 0,
                    });
                }, value: value?.max, type: "number", placeholder: "Max", ...props, 
                // @ts-ignore
                style: Object.assign({ width: fieldWidth / 2 }, props?.style) })));
    }
    if (type === 'checkbox') {
        return (react_1.default.createElement(__1.Input, { label: label, type: "checkbox", value: value, autoFocus: autoFocus, onChange: (v) => onChange(field, v), ...props, 
            // @ts-ignore
            style: props?.style }));
    }
    const validateResult = validation ? validation(value) : true;
    const newRegExp = meta?.regex ? new RegExp(meta?.regex) : false;
    const isString = typeof validateResult === 'string';
    const isError = newRegExp
        ? !newRegExp.test(value)
        : isString
            ? true
            : !validateResult;
    // console.log(newRegExp ? newRegExp.test(value) : label)
    return (react_1.default.createElement(__1.Input, { min: meta?.minimum, max: meta?.maximum, maxLength: meta?.maxChar, integer: type === 'integer' ? true : undefined, error: isError, message: isError && isString ? validateResult : undefined, autoFocus: autoFocus, value: value ?? '', clearButton: true, 
        //  @ts-ignore
        type: 
        //@ts-ignore
        type === 'integer' || type === 'timestamp' || type === 'int'
            ? 'number'
            : type === 'string' ||
                type === 'id' ||
                type === 'reference' ||
                //@ts-ignore
                type === 'url'
                ? 'text'
                : type, onChange: (v) => onChange(field, v), ...props, 
        // @ts-ignore
        style: Object.assign({ width: '100%', gap: noLabel ? 20 : 0 }, props?.style) }));
};
const FormItem = (props) => {
    let { label, field, type, meta, description } = props.item;
    if (!label) {
        if (meta?.label) {
            label = meta?.label;
        }
        else if (meta?.name) {
            label = meta?.name;
        }
        else {
            label = (0, react_1.useMemo)(() => field[0].toUpperCase() + field.slice(1).replace('.', ' '), [field]);
        }
    }
    if (!description && meta?.description) {
        description = meta?.description;
    }
    if (meta?.isLinkedField) {
        return react_1.default.createElement(react_1.default.Fragment, null);
    }
    if (props.noLabel ||
        type === 'array' ||
        type === 'references' ||
        type === 'set')
        return (react_1.default.createElement("div", { style: {
                position: 'relative',
                pointerEvents: meta?.readOnly ? 'none' : 'auto',
                opacity: meta?.readOnly ? '0.4' : '1',
            } },
            react_1.default.createElement(FormItemInner, { ...props, item: { ...props.item, label, description } }),
            react_1.default.createElement(inlines_1.styled.div, { style: {
                    position: 'absolute',
                    display: 'flex',
                    alignItems: 'center',
                    top: 0,
                    bottom: 0,
                    right: 13,
                } }, (props.value === '' || type === 'boolean') && (react_1.default.createElement(icons_1.IconClose, { onClick: props.deleteFunc })))));
    return (react_1.default.createElement("span", { style: {
            pointerEvents: meta?.readOnly ? 'none' : 'auto',
            opacity: meta?.readOnly ? '0.4' : '1',
        } },
        react_1.default.createElement(Label_1.Label, { description: description, label: label },
            react_1.default.createElement(FormItemInner, { ...props }))));
};
exports.FormItem = FormItem;
//# sourceMappingURL=Item.js.map