"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EntityChangesGroup = void 0;
var react_1 = __importStar(require("react"));
var react_context_selector_1 = require("@fluentui/react-context-selector");
var ramda_1 = require("ramda");
var Accordion_1 = __importDefault(require("@mui/material/Accordion"));
var AccordionSummary_1 = __importDefault(require("@mui/material/AccordionSummary"));
var AccordionDetails_1 = __importDefault(require("@mui/material/AccordionDetails"));
var ExpandMore_1 = __importDefault(require("@mui/icons-material/ExpandMore"));
var useChangesList_1 = require("../../../hooks/useChangesList");
var DCREntityUriLink_1 = require("../../../DCREntityUriLink/DCREntityUriLink");
var ChangeItemRow_1 = require("../ChangeItemRow/ChangeItemRow");
var MdmModuleContext_1 = require("../../../../../contexts/MdmModuleContext");
var AddedAttributesContext_1 = require("../../../contexts/AddedAttributesContext");
var ScrollToAddedAttributeContext_1 = require("../../../contexts/ScrollToAddedAttributeContext");
var AttributesChangesContext_1 = require("../../../AttributesChanges/AttributesChangesContext");
var common_1 = require("../../../helpers/common");
var moreAttributesScope_1 = require("../../../helpers/moreAttributesScope");
var helpers_1 = require("../../helpers/helpers");
var changesList_1 = require("../../helpers/changesList");
var addedAttributes_1 = require("../../helpers/addedAttributes");
var merge_1 = require("../../../helpers/merge");
var useDcrReviewAllowAddAttributes_1 = require("../../hooks/useDcrReviewAllowAddAttributes");
var editors_1 = require("../editors");
var EntityChangesGroup_module_css_1 = __importDefault(require("./EntityChangesGroup.module.css"));
var EntityChangesGroup = function (_a) {
    var task = _a.task, dcr = _a.dcr, entityInfo = _a.entityInfo, relationsInfo = _a.relationsInfo;
    var metadata = (0, MdmModuleContext_1.useMdmMetadata)();
    var dcrUri = (0, common_1.getDCRUri)(task.objectURIs);
    var _b = dcr || {}, changes = _b.changes, objectsInfo = _b.objectsInfo;
    var addAddedAttributes = (0, react_context_selector_1.useContextSelector)(AddedAttributesContext_1.AddedAttributesContext, function (ctx) { return ctx.addAddedAttributes; });
    var highlight = (0, react_1.useContext)(ScrollToAddedAttributeContext_1.ScrollToAddedAttributeContext).highlight;
    var allowAddAttributes = (0, useDcrReviewAllowAddAttributes_1.useDcrReviewAllowAddAttributes)();
    var rawChangesList = (0, useChangesList_1.useChangesList)({
        changes: changes,
        entityInfo: entityInfo,
        relationsInfo: relationsInfo
    });
    var changesList = (0, react_1.useMemo)(function () { return (0, changesList_1.prepareChangesList)(rawChangesList); }, [rawChangesList]);
    var objectUriByChangeIndex = (0, react_1.useMemo)(function () {
        var _a, _b;
        var result = [];
        var currentObjectUri = entityInfo.uri;
        for (var _i = 0, changesList_2 = changesList; _i < changesList_2.length; _i++) {
            var item = changesList_2[_i];
            if (!(0, helpers_1.isDiffChange)(item)) {
                currentObjectUri = entityInfo.uri;
            }
            else if ((0, helpers_1.isRelationRow)(item)) {
                currentObjectUri = (_b = (_a = item.attributeValue) === null || _a === void 0 ? void 0 : _a.uri) !== null && _b !== void 0 ? _b : entityInfo.uri;
            }
            result.push(currentObjectUri);
        }
        return result;
    }, [changesList, entityInfo.uri]);
    var entityAttributeTypes = (0, react_1.useMemo)(function () {
        if (!(0, ramda_1.isNil)(entityInfo.isExist)) {
            return (0, moreAttributesScope_1.getAvailableAttributeTypesForEntity)(metadata, entityInfo.type);
        }
        return [];
    }, [metadata, entityInfo.type, entityInfo.isExist]);
    var relationAttributeTypesMap = (0, react_1.useMemo)(function () {
        var map = new Map();
        for (var _i = 0, relationsInfo_1 = relationsInfo; _i < relationsInfo_1.length; _i++) {
            var relationInfo = relationsInfo_1[_i];
            if (!map.has(relationInfo.type)) {
                map.set(relationInfo.type, (0, moreAttributesScope_1.getAvailableAttributeTypesForRelation)(metadata, relationInfo.type));
            }
        }
        return map;
    }, [metadata, relationsInfo]);
    var handleAddAttributes = (0, react_1.useCallback)(function (_a) {
        var objectUri = _a.objectUri, parentLineId = _a.parentLineId, parentId = _a.parentId, changeOverrides = _a.changeOverrides;
        return function (attributeTypes) {
            var addedIds = addAddedAttributes({
                attributeTypes: attributeTypes,
                objectUri: objectUri,
                parentLineId: parentLineId,
                parentId: parentId,
                changeOverrides: changeOverrides
            });
            highlight(addedIds);
        };
    }, [addAddedAttributes, highlight]);
    var handleAddNestedAttributes = (0, react_1.useCallback)(function (change, objectUri) { return function (attributeTypes) {
        var _a, _b, _c, _d, _e;
        var parentUri = (_a = change.attributeType) === null || _a === void 0 ? void 0 : _a.uri;
        var parentAttrs = attributeTypes.filter(function (attr) { return attr.uri === parentUri; });
        var subAttrs = attributeTypes.filter(function (attr) { return attr.uri !== parentUri; });
        var childOverrides = (0, addedAttributes_1.extractChangeOverrides)(change);
        var siblingOverrides = (0, addedAttributes_1.getParentChangeOverrides)(change);
        if (parentAttrs.length > 0) {
            var lineId = (_c = (_b = change.lineIds) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : (_d = (0, merge_1.extractLineIds)(change.newValue)) === null || _d === void 0 ? void 0 : _d[0];
            var addedId = (0, addedAttributes_1.getAddedId)(change);
            if (lineId && (0, addedAttributes_1.isRootAddedAttribute)(lineId)) {
                handleAddAttributes({
                    objectUri: objectUri,
                    changeOverrides: siblingOverrides
                })(parentAttrs);
            }
            else if (lineId) {
                handleAddAttributes({
                    parentLineId: (0, addedAttributes_1.getParentLineId)(lineId),
                    parentId: addedId ? (0, addedAttributes_1.getParentAddedId)(addedId) : undefined,
                    changeOverrides: siblingOverrides
                })(parentAttrs);
            }
            else {
                handleAddAttributes({
                    objectUri: objectUri,
                    changeOverrides: siblingOverrides
                })(parentAttrs);
            }
        }
        if (subAttrs.length > 0) {
            var parentLineId = (_e = change.lineIds) === null || _e === void 0 ? void 0 : _e[0];
            var parentId = change.addedId;
            if (parentLineId || parentId) {
                handleAddAttributes({ parentLineId: parentLineId, parentId: parentId, changeOverrides: childOverrides })(subAttrs);
            }
            else {
                handleAddAttributes({
                    objectUri: objectUri,
                    changeOverrides: childOverrides
                })(subAttrs);
            }
        }
    }; }, [handleAddAttributes]);
    return (react_1.default.createElement(AttributesChangesContext_1.AttributesChangesContext.Provider, { value: objectsInfo },
        react_1.default.createElement(Accordion_1.default, { className: EntityChangesGroup_module_css_1.default.entityGroup, defaultExpanded: true, "data-reltio-id": "entity-changes-group" },
            react_1.default.createElement(AccordionSummary_1.default, { expandIcon: react_1.default.createElement(ExpandMore_1.default, null), className: EntityChangesGroup_module_css_1.default.entityHeader, classes: {
                    content: EntityChangesGroup_module_css_1.default.accordionContent
                } },
                react_1.default.createElement(DCREntityUriLink_1.DCREntityUriLink, { entityInfo: entityInfo, changes: changes, dcrUri: dcrUri, className: EntityChangesGroup_module_css_1.default.entityTitle })),
            react_1.default.createElement(AccordionDetails_1.default, { className: EntityChangesGroup_module_css_1.default.attributesList },
                allowAddAttributes && entityAttributeTypes.length > 0 && (react_1.default.createElement(editors_1.MoreAttributesEditor, { data: entityAttributeTypes, onApply: handleAddAttributes({ objectUri: entityInfo.uri }) })),
                changesList.map(function (item, index) {
                    var _a, _b, _c, _d, _e, _f;
                    if (!(0, helpers_1.isDiffChange)(item)) {
                        return (react_1.default.createElement("div", { key: "title-".concat(index), className: EntityChangesGroup_module_css_1.default.titleChangeItem }, item.label));
                    }
                    var relationAttrs = item.relationType
                        ? ((_a = relationAttributeTypesMap.get(item.relationType.uri)) !== null && _a !== void 0 ? _a : [])
                        : [];
                    var nestedAttrs = (0, helpers_1.isNestedOrReferenceParent)(item)
                        ? (0, moreAttributesScope_1.getAvailableSubAttributesForNestedOrReference)(metadata, item.attributeType)
                        : [];
                    var changeKey = (_d = (_b = item.addedId) !== null && _b !== void 0 ? _b : (_c = item.attributeValue) === null || _c === void 0 ? void 0 : _c.uri) !== null && _d !== void 0 ? _d : "change-".concat(index);
                    return (react_1.default.createElement(react_1.default.Fragment, { key: changeKey },
                        react_1.default.createElement(ChangeItemRow_1.ChangeItemRow, { change: item, entityInfo: entityInfo }),
                        allowAddAttributes && (0, helpers_1.isRelationRow)(item) && (react_1.default.createElement(editors_1.MoreAttributesEditor, { data: relationAttrs, change: item, onApply: handleAddAttributes({
                                objectUri: (_e = item === null || item === void 0 ? void 0 : item.attributeValue) === null || _e === void 0 ? void 0 : _e.uri,
                                parentLineId: (_f = item.lineIds) === null || _f === void 0 ? void 0 : _f[0]
                            }) })),
                        allowAddAttributes && (0, helpers_1.isNestedOrReferenceParent)(item) && (react_1.default.createElement(editors_1.MoreAttributesEditor, { data: nestedAttrs, change: item, parent: item.attributeType, onApply: handleAddNestedAttributes(item, objectUriByChangeIndex[index]) }))));
                })))));
};
exports.EntityChangesGroup = EntityChangesGroup;
