"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddedAttributesProvider = exports.AddedAttributesContext = exports.ADDED_CHANGE_ID_PREFIX = exports.ADDED_ID_SEPARATOR = void 0;
var react_1 = __importStar(require("react"));
var react_context_selector_1 = require("@fluentui/react-context-selector");
var nanoid_1 = require("nanoid");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var MdmModuleContext_1 = require("../../../../contexts/MdmModuleContext");
var moreAttributesScope_1 = require("../../helpers/moreAttributesScope");
exports.ADDED_ID_SEPARATOR = '|';
exports.ADDED_CHANGE_ID_PREFIX = "added".concat(exports.ADDED_ID_SEPARATOR);
exports.AddedAttributesContext = (0, react_context_selector_1.createContext)({
    getAddedAttributes: undefined,
    addAddedAttributes: undefined,
    removeAddedAttribute: undefined,
    updateAddedAttributeRefEntity: undefined,
    resetState: undefined
});
var getInitialAttributeValue = function (attrType) {
    if ((0, mdm_sdk_1.isComplexAttribute)(attrType) || (0, mdm_sdk_1.isImage)(attrType))
        return undefined;
    var _a = (0, mdm_sdk_1.createNewAttributeValue)(attrType), value = _a.value, lookupCode = _a.lookupCode;
    if (value === '' && !lookupCode)
        return undefined;
    return lookupCode ? { value: value, lookupCode: lookupCode } : { value: value };
};
var generateAddedAttributeId = function (parentId) {
    return parentId ? "".concat(parentId).concat(exports.ADDED_ID_SEPARATOR).concat((0, nanoid_1.nanoid)()) : "".concat(exports.ADDED_CHANGE_ID_PREFIX).concat((0, nanoid_1.nanoid)());
};
var createAddedAttribute = function (_a) {
    var attributeType = _a.attributeType, objectUri = _a.objectUri, parentLineId = _a.parentLineId, parentId = _a.parentId, changeOverrides = _a.changeOverrides;
    var finalChangeOverrides = changeOverrides
        ? __assign(__assign(__assign({}, changeOverrides), (changeOverrides.attributePath && {
            attributePath: "".concat(changeOverrides.attributePath, "/").concat(attributeType.name)
        })), (changeOverrides.refAttributeType && {
            refAttributeType: "".concat(changeOverrides.refAttributeType, "/attributes/").concat(attributeType.name)
        })) : undefined;
    var initialValue = getInitialAttributeValue(attributeType);
    return __assign({ attributeType: attributeType, id: generateAddedAttributeId(parentId), objectUri: objectUri, parentLineId: parentLineId, parentId: parentId, changeOverrides: finalChangeOverrides }, (initialValue && { initialValue: initialValue }));
};
var AddedAttributesProvider = function (_a) {
    var children = _a.children;
    var metadata = (0, MdmModuleContext_1.useMdmMetadata)();
    var _b = (0, react_1.useState)([]), state = _b[0], setState = _b[1];
    var getAddedAttributes = (0, react_1.useCallback)(function () { return state; }, [state]);
    var createAddedAttributes = (0, react_1.useCallback)(function (_a) {
        var attributeType = _a.attributeType, objectUri = _a.objectUri, parentLineId = _a.parentLineId, parentId = _a.parentId, changeOverrides = _a.changeOverrides;
        var addedAttribute = createAddedAttribute({
            attributeType: attributeType,
            objectUri: objectUri,
            parentLineId: parentLineId,
            parentId: parentId,
            changeOverrides: changeOverrides
        });
        var result = [addedAttribute];
        if ((0, mdm_sdk_1.isComplexAttribute)(attributeType)) {
            var subAttributes = (0, moreAttributesScope_1.getAvailableSubAttributesForNestedOrReference)(metadata, attributeType);
            for (var _i = 0, subAttributes_1 = subAttributes; _i < subAttributes_1.length; _i++) {
                var attr = subAttributes_1[_i];
                if (attr.required) {
                    result.push.apply(result, createAddedAttributes({
                        attributeType: attr,
                        objectUri: objectUri,
                        parentId: addedAttribute.id
                    }));
                }
                else {
                    result.push(createAddedAttribute({
                        attributeType: attr,
                        objectUri: objectUri,
                        parentId: addedAttribute.id
                    }));
                }
            }
        }
        return result;
    }, [metadata]);
    var addAddedAttributes = (0, react_1.useCallback)(function (_a) {
        var attributeTypes = _a.attributeTypes, objectUri = _a.objectUri, parentLineId = _a.parentLineId, parentId = _a.parentId, changeOverrides = _a.changeOverrides;
        if (attributeTypes.length === 0)
            return [];
        var addedIds = [];
        setState(function (prev) {
            var newAddedAttributes = attributeTypes.flatMap(function (attributeType) {
                return createAddedAttributes({ attributeType: attributeType, objectUri: objectUri, parentLineId: parentLineId, parentId: parentId, changeOverrides: changeOverrides });
            });
            addedIds.push.apply(addedIds, newAddedAttributes.map(function (attr) { return attr.id; }));
            return __spreadArray(__spreadArray([], prev, true), newAddedAttributes, true);
        });
        return addedIds;
    }, [createAddedAttributes]);
    var removeAddedAttribute = (0, react_1.useCallback)(function (id) {
        setState(function (prev) {
            return prev.filter(function (addedAttribute) {
                return addedAttribute.id !== id && !addedAttribute.id.startsWith("".concat(id).concat(exports.ADDED_ID_SEPARATOR));
            });
        });
    }, []);
    var updateAddedAttributeRefEntity = (0, react_1.useCallback)(function (id, refEntity) {
        setState(function (prev) { return prev.map(function (attr) { return (attr.id === id ? __assign(__assign({}, attr), { refEntity: refEntity }) : attr); }); });
    }, []);
    var resetState = (0, react_1.useCallback)(function () {
        setState([]);
    }, []);
    var value = (0, react_1.useMemo)(function () { return ({
        getAddedAttributes: getAddedAttributes,
        addAddedAttributes: addAddedAttributes,
        removeAddedAttribute: removeAddedAttribute,
        updateAddedAttributeRefEntity: updateAddedAttributeRefEntity,
        resetState: resetState
    }); }, [getAddedAttributes, addAddedAttributes, removeAddedAttribute, updateAddedAttributeRefEntity, resetState]);
    return react_1.default.createElement(exports.AddedAttributesContext.Provider, { value: value }, children);
};
exports.AddedAttributesProvider = AddedAttributesProvider;
