import React, { useCallback, useEffect, useRef, useState } from 'react';
import { isNil } from 'ramda';
import { createContext } from '@fluentui/react-context-selector';
export var ChangeRequestEditorContext = createContext({
    updateChange: undefined,
    getLineData: undefined,
    getLinesByChangeId: undefined,
    rejectChange: undefined,
    revertChangeUpdateOrReject: undefined,
    deleteLineData: undefined,
    getIsParentLineRejected: undefined,
    getIsLineRejected: undefined,
    getIsLineUpdated: undefined,
    getAllChanges: undefined,
    setErrors: undefined,
    getErrorByLineId: undefined,
    getErrors: undefined,
    resetState: undefined
});
var emptyArray = [];
var removeLineDataFromMap = function (map, lineIds) {
    var newMap = new Map(map);
    lineIds.forEach(function (id) {
        newMap.forEach(function (_, key) {
            if (key.startsWith("".concat(id, "/")) || key === id) {
                newMap.delete(key);
            }
        });
    });
    return newMap;
};
export var ChangeRequestEditorProvider = function (_a) {
    var children = _a.children;
    var _b = useState(new Map()), lineDataMap = _b[0], setLineDataMap = _b[1];
    var lineDataMapRef = useRef(lineDataMap);
    var _c = useState([]), errors = _c[0], setErrors = _c[1];
    var updateChange = useCallback(function (lineIds, data) {
        setLineDataMap(function (prevMap) {
            var newMap = new Map(prevMap);
            lineIds.forEach(function (id) {
                newMap.set(id, { value: data });
            });
            return newMap;
        });
    }, []);
    var rejectChange = useCallback(function (lineIds) {
        setLineDataMap(function (prevMap) {
            var newMap = new Map(prevMap);
            lineIds.forEach(function (id) {
                newMap.set(id, { isRejected: true });
            });
            return newMap;
        });
    }, []);
    var revertChangeUpdateOrReject = useCallback(function (lineIds) {
        setLineDataMap(function (prevMap) { return removeLineDataFromMap(prevMap, lineIds); });
    }, []);
    var deleteLineData = useCallback(function (lineIds) {
        setLineDataMap(function (prevMap) {
            var newMap = removeLineDataFromMap(prevMap, lineIds);
            var _loop_1 = function (lineId) {
                var parts = lineId.split('/');
                var deletedIndex = parseInt(parts[parts.length - 1]);
                if (isNaN(deletedIndex))
                    return "continue";
                var prefix = parts.slice(0, -1).join('/') + '/';
                var toRename = [];
                newMap.forEach(function (data, key) {
                    if (!key.startsWith(prefix))
                        return;
                    var rest = key.slice(prefix.length);
                    var indexStr = rest.split('/')[0];
                    var index = parseInt(indexStr);
                    if (isNaN(index) || index <= deletedIndex)
                        return;
                    var newKey = prefix + String(index - 1) + rest.slice(indexStr.length);
                    toRename.push({ oldKey: key, newKey: newKey, data: data });
                });
                for (var _a = 0, toRename_1 = toRename; _a < toRename_1.length; _a++) {
                    var oldKey = toRename_1[_a].oldKey;
                    newMap.delete(oldKey);
                }
                for (var _b = 0, toRename_2 = toRename; _b < toRename_2.length; _b++) {
                    var _c = toRename_2[_b], newKey = _c.newKey, data = _c.data;
                    newMap.set(newKey, data);
                }
            };
            for (var _i = 0, lineIds_1 = lineIds; _i < lineIds_1.length; _i++) {
                var lineId = lineIds_1[_i];
                _loop_1(lineId);
            }
            return newMap;
        });
    }, []);
    var getLineData = useCallback(function (lineId) {
        return lineDataMap.get(lineId);
    }, [lineDataMap]);
    var getIsLineRejected = useCallback(function (lineId) {
        var _a;
        return ((_a = lineDataMap.get(lineId)) === null || _a === void 0 ? void 0 : _a.isRejected) || false;
    }, [lineDataMap]);
    var getIsParentLineRejected = useCallback(function (lineId) {
        var lineIdParts = (lineId || '').split('/');
        var possibleRejectedIds = Array.from({ length: lineIdParts.length - 1 }).reduce(function (ids, _, index) {
            return ids.concat(lineIdParts.slice(0, index + 1).join('/'));
        }, []);
        return possibleRejectedIds.some(function (lineId) { var _a; return (_a = lineDataMap.get(lineId)) === null || _a === void 0 ? void 0 : _a.isRejected; });
    }, [lineDataMap]);
    var getIsLineUpdated = useCallback(function (lineId) {
        var _a;
        return !isNil((_a = lineDataMap.get(lineId)) === null || _a === void 0 ? void 0 : _a.value);
    }, [lineDataMap]);
    var getLinesByChangeId = useCallback(function (changeId) {
        return Array.from(lineDataMapRef.current).filter(function (_a) {
            var key = _a[0], _value = _a[1];
            return key.split('/')[1] === changeId;
        });
    }, []);
    var getAllChanges = useCallback(function () {
        var changes = Array.from(lineDataMapRef.current).map(function (_a) {
            var lineId = _a[0], data = _a[1];
            return ({ lineId: lineId, data: data });
        });
        return changes.length > 0 ? changes : emptyArray;
    }, []);
    useEffect(function () {
        lineDataMapRef.current = lineDataMap;
    }, [lineDataMap]);
    var getErrorByLineId = useCallback(function (lineId) {
        return errors.find(function (_a) {
            var lineIds = _a.lineIds;
            return lineIds.includes(lineId);
        });
    }, [errors]);
    var getErrors = useCallback(function () {
        return errors;
    }, [errors]);
    var resetState = useCallback(function () {
        setLineDataMap(new Map());
        setErrors([]);
    }, []);
    var contextValue = {
        updateChange: updateChange,
        getLineData: getLineData,
        getLinesByChangeId: getLinesByChangeId,
        rejectChange: rejectChange,
        revertChangeUpdateOrReject: revertChangeUpdateOrReject,
        deleteLineData: deleteLineData,
        getIsParentLineRejected: getIsParentLineRejected,
        getIsLineRejected: getIsLineRejected,
        getIsLineUpdated: getIsLineUpdated,
        getAllChanges: getAllChanges,
        setErrors: setErrors,
        getErrorByLineId: getErrorByLineId,
        getErrors: getErrors,
        resetState: resetState
    };
    return React.createElement(ChangeRequestEditorContext.Provider, { value: contextValue }, children);
};
