"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HistoryTree = void 0;
var react_1 = __importStar(require("react"));
var react_resize_detector_1 = __importDefault(require("react-resize-detector"));
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var ramda_1 = require("ramda");
var classnames_1 = __importDefault(require("classnames"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var Button_1 = __importDefault(require("@mui/material/Button"));
var HistoryRow_1 = require("../HistoryRow");
var HistoryGraph_1 = require("../HistoryGraph");
var LinearLoadIndicator_1 = require("../../../LinearLoadIndicator");
var MdmModuleContext_1 = require("../../../contexts/MdmModuleContext");
var styles_1 = require("./styles");
var HistoryTree = function (_a) {
    var _b;
    var historyData = _a.historyData, isLoading = _a.isLoading, canLoadMore = _a.canLoadMore, onLoadMore = _a.onLoadMore, entityUri = _a.entityUri, historyEvent = _a.historyEvent, findPreviousChange = _a.findPreviousChange;
    var styles = (0, styles_1.useStyles)();
    var _c = (0, react_1.useState)({ historyLanes: {}, rows: [] }), graphData = _c[0], setGraphData = _c[1];
    var _d = (0, react_1.useState)(false), isScrollable = _d[0], setIsScrollable = _d[1];
    var _e = (0, react_1.useState)(-1), selectedIndex = _e[0], setSelectedIndex = _e[1];
    var setHistoryEvent = (0, MdmModuleContext_1.useMdmAction)('setHistoryEvent');
    var clearHistoryEvent = (0, MdmModuleContext_1.useMdmAction)('clearHistoryEvent');
    var modeUpdateRequested = (0, MdmModuleContext_1.useMdmAction)('modeUpdateRequested');
    var metadata = (0, MdmModuleContext_1.useMdmMetadata)();
    var isEditableMode = (0, MdmModuleContext_1.useMdmIsEditableMode)();
    (0, react_1.useEffect)(function () {
        if ((0, ramda_1.isNil)(historyEvent)) {
            setSelectedIndex(0);
            return;
        }
        var isCurrentEventChange = function (change) {
            return (change === null || change === void 0 ? void 0 : change.uri) === ((historyEvent === null || historyEvent === void 0 ? void 0 : historyEvent.overrideUri) || entityUri) && (change === null || change === void 0 ? void 0 : change.timestamp) === (historyEvent === null || historyEvent === void 0 ? void 0 : historyEvent.aStamp);
        };
        var selectedChangeByIndex = selectedIndex !== -1 ? historyData.rows[selectedIndex] : null;
        var currentEventChangeIndex = historyData.rows.findIndex(function (change) { return isCurrentEventChange(change); });
        setSelectedIndex(isCurrentEventChange(selectedChangeByIndex) ? selectedIndex : currentEventChangeIndex);
    }, [historyData.rows, historyEvent]);
    var graphRef = (0, react_1.useRef)(null);
    var rowsRef = (0, react_1.useCallback)(function (node) {
        var _a;
        if (!(0, ramda_1.isNil)(node)) {
            var rows = (_a = historyData.rows) === null || _a === void 0 ? void 0 : _a.map(function (item, i) { var _a; return (__assign(__assign({}, item), { height: (_a = node.childNodes[i]) === null || _a === void 0 ? void 0 : _a.clientHeight })); });
            setGraphData({ historyLanes: historyData.historyLanes, rows: rows });
        }
    }, [historyData]);
    var handleGraphScroll = function () {
        var _a = (graphRef === null || graphRef === void 0 ? void 0 : graphRef.current) || {}, scrollWidth = _a.scrollWidth, clientWidth = _a.clientWidth, scrollLeft = _a.scrollLeft;
        setIsScrollable(scrollLeft < scrollWidth - clientWidth);
    };
    var handleHistoryCircleMouseOver = function (uri, timestamp, index) {
        if ((0, ramda_1.isNil)(graphData.rows[index].label)) {
            var options = { time: timestamp, select: 'crosswalks' };
            (0, mdm_sdk_1.getEntity)(uri, options)
                .then(function (_a) {
                var crosswalks = _a.crosswalks;
                var label = crosswalks
                    ? (0, ramda_1.uniqBy)((0, ramda_1.prop)('type'), crosswalks)
                        .map(function (cw) {
                        var crosswalkType = (0, mdm_sdk_1.getCrosswalkType)(metadata, cw.type);
                        return crosswalkType ? crosswalkType.label : null;
                    })
                        .filter(ramda_1.identity)
                        .join(', ')
                    : ui_i18n_1.default.text('No data');
                setGraphData(function (prevGraphData) { return (__assign(__assign({}, prevGraphData), { rows: prevGraphData.rows.map(function (row) { return (row.index === index ? __assign(__assign({}, row), { label: label }) : row); }) })); });
            })
                .catch(function (error) {
                console.warn(error);
            });
        }
    };
    var handleHistoryRowClick = function (index, change, isSelected, isCurrent) {
        if (isEditableMode) {
            modeUpdateRequested(mdm_sdk_1.Mode.Viewing);
        }
        if ((isCurrent && !isSelected) || (!isCurrent && isSelected)) {
            clearHistoryEvent();
            setSelectedIndex(0);
        }
        else if (!isCurrent && !isSelected) {
            var aChange = findPreviousChange(index - 1, change.uri || entityUri);
            var bChange = findPreviousChange(index, change.uri || entityUri);
            var aStamp = aChange === null || aChange === void 0 ? void 0 : aChange.timestamp;
            var bStamp = bChange === null || bChange === void 0 ? void 0 : bChange.timestamp;
            var overrideUri = (change === null || change === void 0 ? void 0 : change.uri) === entityUri ? null : change === null || change === void 0 ? void 0 : change.uri;
            setHistoryEvent({ aStamp: aStamp, bStamp: bStamp, overrideUri: overrideUri });
            setSelectedIndex(index);
        }
    };
    return (react_1.default.createElement("div", { className: styles.historyTree, "data-reltio-id": "history-tree" },
        isLoading && react_1.default.createElement(LinearLoadIndicator_1.LinearLoadIndicator, null),
        react_1.default.createElement("div", { className: (0, classnames_1.default)(styles.graph, (_b = {}, _b[styles.shadow] = isScrollable, _b)), onScroll: handleGraphScroll, ref: graphRef },
            react_1.default.createElement(HistoryGraph_1.HistoryGraph, { onHistoryCircleMouseOver: handleHistoryCircleMouseOver, graphData: graphData }),
            react_1.default.createElement(react_resize_detector_1.default, { handleWidth: true, onResize: handleGraphScroll })),
        react_1.default.createElement("div", { ref: rowsRef, className: styles.history }, historyData.rows.map(function (change, i) {
            var isSelected = i === selectedIndex;
            var isCurrent = i === 0;
            return (react_1.default.createElement(HistoryRow_1.HistoryRow, { key: "row-".concat(i), change: change, isCurrent: isCurrent, isSelected: isSelected, onClick: function () { return handleHistoryRowClick(i, change, isSelected, isCurrent); } }));
        })),
        canLoadMore && (react_1.default.createElement("div", { className: styles.buttonContainer },
            react_1.default.createElement(Button_1.default, { color: "primary", onClick: function () { return onLoadMore(); } }, ui_i18n_1.default.text('Show more'))))));
};
exports.HistoryTree = HistoryTree;
