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);
};
import React, { memo, useCallback, useEffect, useMemo, useState } from 'react';
import classnames from 'classnames';
import i18n from 'ui-i18n';
import { always, either, filter, isNil, keys, map, pipe, without, identity, both, move } from 'ramda';
import { debounce, findAttributeTypeByUri, isReadableAttribute, makeAttrTypeUri } from '@reltio/mdm-sdk';
import { BasicTable } from '../../../BasicTable';
import { ColumnsSettings } from '../../../ColumnsSettings';
import { useDynamicRowCellHeight } from '../../../hooks/useDynamicRowCellHeight';
import { BasicViewHeader } from '../../../BasicViewHeader';
import { LinearLoadIndicator } from '../../../LinearLoadIndicator';
import { ConfirmDeleteDialog } from '../../../ConfirmDeleteDialog';
import { useMdmMetadata } from '../../../contexts/MdmModuleContext';
import { COLUMNS_DATA, DEFAULT_VISIBLE_COLUMNS, getBasicTableColumnsData, getBasicTableRowsData } from './helpers';
import { ConfirmEditIgnoredDialog } from './components/ConfirmEditIgnoredDialog';
import { CommonRowCellRenderer } from './components/CommonRowCellRenderer';
import { LazyRenderer } from '../../../LazyRenderer';
import { SyncedValueHeightsProvider } from '../contexts/SyncedValueHeightsContext';
import { useStyles } from './styles';
var DEFAULT_ROW_HEIGHT = 68;
var getIdFromRowValue = function (rowValue) { return rowValue.ovValues.attributeType.uri; };
var getRowCellKey = function (_a) {
    var id = _a.columnData.id, cellIndex = _a.cellIndex, rowValue = _a.rowValue;
    return "".concat(id, "[").concat(getIdFromRowValue(rowValue), "][").concat(cellIndex, "]");
};
var debouncedNotifyLazyRenderer = debounce(LazyRenderer.notify, 0);
var AttributesTable = function (_a) {
    var entity = _a.entity, isLoading = _a.isLoading, crosswalksMap = _a.crosswalksMap, _b = _a.visibleColumns, visibleColumns = _b === void 0 ? DEFAULT_VISIBLE_COLUMNS : _b, onChangeVisibleColumns = _a.onChangeVisibleColumns, readOnly = _a.readOnly, _c = _a.onDelete, onDelete = _c === void 0 ? identity : _c, _d = _a.onPin, onPin = _d === void 0 ? identity : _d, _e = _a.onIgnore, onIgnore = _e === void 0 ? identity : _e, _f = _a.onEdit, onEdit = _f === void 0 ? identity : _f, _g = _a.onAdd, onAdd = _g === void 0 ? identity : _g, emptyTempAttributeUris = _a.emptyTempAttributeUris, selectedAttributeTypes = _a.selectedAttributeTypes, _h = _a.onSelectAttributeTypes, onSelectAttributeTypes = _h === void 0 ? identity : _h, additionalHeaderItems = _a.additionalHeaderItems, className = _a.className, activeSurvivorshipGroupUri = _a.activeSurvivorshipGroupUri, tableRef = _a.tableRef;
    var styles = useStyles();
    var metadata = useMdmMetadata();
    var visibleColumnsData = useMemo(function () {
        return pipe(filter(function (_a) {
            var id = _a.id;
            return visibleColumns.includes(id);
        }), getBasicTableColumnsData)(COLUMNS_DATA);
    }, [visibleColumns]);
    var _j = entity || {}, parentTypeUri = _j.type, parentUri = _j.uri, _k = _j.attributes, attributes = _k === void 0 ? {} : _k;
    useEffect(function () {
        if (entity && isNil(selectedAttributeTypes)) {
            var initialAttrTypes = pipe(keys, without(['paging']), map(makeAttrTypeUri(parentTypeUri)), map(function (attrTypeUri) { return findAttributeTypeByUri(metadata, attrTypeUri, parentTypeUri); }), filter(both(identity, isReadableAttribute)))(attributes);
            onSelectAttributeTypes(initialAttrTypes);
        }
    }, [entity, selectedAttributeTypes]);
    var rowsData = useMemo(function () {
        return parentTypeUri
            ? getBasicTableRowsData(metadata, parentTypeUri, selectedAttributeTypes, visibleColumns, crosswalksMap, attributes, activeSurvivorshipGroupUri)
            : [];
    }, [
        metadata,
        parentTypeUri,
        selectedAttributeTypes,
        visibleColumns,
        attributes,
        crosswalksMap,
        activeSurvivorshipGroupUri
    ]);
    var _l = useDynamicRowCellHeight(getRowCellKey), getDynamicRowCellHeight = _l.getDynamicRowCellHeight, changeRowCellHeight = _l.changeRowCellHeight;
    var renderRowCell = useCallback(function (props) { return React.createElement(CommonRowCellRenderer, __assign({ changeRowCellHeight: changeRowCellHeight }, props)); }, [changeRowCellHeight]);
    var getRowCellHeight = useCallback(either(getDynamicRowCellHeight, always(DEFAULT_ROW_HEIGHT)), [
        getDynamicRowCellHeight
    ]);
    useEffect(function () {
        debouncedNotifyLazyRenderer();
    }, [getRowCellHeight]);
    var _m = useState(null), pendingDeletion = _m[0], setPendingDeletion = _m[1];
    var _o = useState(null), pendingIgnoredEditing = _o[0], setPendingIgnoredEditing = _o[1];
    var handleEdit = useCallback(function (event) {
        if (event.attributeValue.ignored) {
            setPendingIgnoredEditing(event);
        }
        else {
            onEdit(event);
        }
    }, [onEdit, setPendingIgnoredEditing]);
    var handleReorderAttributeTypes = useCallback(function (oldPosition, newPosition) {
        onSelectAttributeTypes(move(oldPosition, newPosition, selectedAttributeTypes));
    }, [onSelectAttributeTypes, selectedAttributeTypes]);
    var handleDelete = useCallback(pendingDeletion ? function () { return onDelete(pendingDeletion); } : identity, [
        pendingDeletion,
        onDelete
    ]);
    var tableContext = useMemo(function () { return ({
        onDelete: setPendingDeletion,
        onPin: onPin,
        onIgnore: onIgnore,
        onEdit: handleEdit,
        onAdd: onAdd,
        parentUri: parentUri,
        parentTypeUri: parentTypeUri,
        selectedAttributeTypes: selectedAttributeTypes,
        onSelectAttributeTypes: onSelectAttributeTypes,
        emptyTempAttributeUris: emptyTempAttributeUris,
        readOnly: readOnly
    }); }, [
        setPendingDeletion,
        onPin,
        onIgnore,
        handleEdit,
        onAdd,
        parentUri,
        parentTypeUri,
        selectedAttributeTypes,
        onSelectAttributeTypes,
        emptyTempAttributeUris,
        readOnly
    ]);
    return (React.createElement("div", { className: classnames(styles.tableContainer, className) },
        React.createElement(BasicViewHeader, { classes: { root: styles.tableHeader, title: styles.tableTitle }, title: i18n.text('Sources') },
            additionalHeaderItems,
            React.createElement(ColumnsSettings, { columnsData: COLUMNS_DATA, selectedColumns: visibleColumns, onChangeColumns: onChangeVisibleColumns })),
        React.createElement("div", { className: styles.tableContent },
            isLoading && React.createElement(LinearLoadIndicator, null),
            React.createElement(SyncedValueHeightsProvider, null,
                React.createElement(BasicTable, { ref: tableRef, fixFirstColumn: true, headRowHeight: 48, defaultColumnWidth: 250, defaultColumnMinWidth: 200, columnsData: visibleColumnsData, dndRowReorderingEnabled: false, dndRowReorderingHandler: handleReorderAttributeTypes, getIdFromRowValue: getIdFromRowValue, rowsData: rowsData, onScroll: debouncedNotifyLazyRenderer, renderRowCell: renderRowCell, getRowCellHeight: getRowCellHeight, context: tableContext }))),
        React.createElement(ConfirmDeleteDialog, { open: !!pendingDeletion, onClose: function () { return setPendingDeletion(null); }, onConfirm: handleDelete }),
        React.createElement(ConfirmEditIgnoredDialog, { open: !!pendingIgnoredEditing, onClose: function () { return setPendingIgnoredEditing(null); }, onConfirmEditWithIgnore: function () { return pendingIgnoredEditing && onEdit(pendingIgnoredEditing); }, onConfirmEditWithoutIgnore: function () {
                if (pendingIgnoredEditing)
                    onEdit(__assign(__assign({}, pendingIgnoredEditing), { clearAttributeFlags: true }));
            } })));
};
export default memo(AttributesTable);
