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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { useState, useCallback, useMemo, useEffect } from 'react';
import i18n from 'ui-i18n';
import { count, length, map, pipe, prop, uniq } from 'ramda';
import { ExportDataFormat, exportData, ExportHeaderOrder, promiseAllSettled, getEntityType, isHiddenAttribute, getFirstLevelSearchUri } from '@reltio/mdm-sdk';
import { useMdmExportPath, useMdmTenant, useMdmMetadata } from '../../contexts/MdmModuleContext';
var ExportFormat;
(function (ExportFormat) {
    ExportFormat["CSVFlattened"] = "csvFlattened";
    ExportFormat["CSVExploded"] = "csvExploded";
    ExportFormat["JSON"] = "json";
})(ExportFormat || (ExportFormat = {}));
var DEFAULT_EXPORT_NAME = 'Untitled Export Job';
// List of basic attributes:
// [createdBy, createdTime, updatedBy, updatedTime, uri, type, endDate, analyticsAttributes, label, secondaryLabel]
var BASIC_ATTRIBUTES_COUNT = 10;
export var useInternalExport = function (_a) {
    var columnsByEntityType = _a.columnsByEntityType, dialogOpen = _a.dialogOpen, filter = _a.filter, activityFilter = _a.activityFilter, isSearchByOv = _a.isSearchByOv;
    var exportPath = useMdmExportPath();
    var tenant = useMdmTenant();
    var metadata = useMdmMetadata();
    var defaultFormat = useMemo(function () {
        return {
            value: ExportFormat.CSVFlattened,
            label: i18n.text('CSV Flattened')
        };
    }, []);
    var _b = useState(''), exportName = _b[0], setExportName = _b[1];
    var _c = useState(), fileFormat = _c[0], setFileFormat = _c[1];
    var _d = useState(false), exportOvOnly = _d[0], setExportOvOnly = _d[1];
    var formatOptions = useMemo(function () {
        return [
            defaultFormat,
            {
                value: ExportFormat.CSVExploded,
                label: i18n.text('CSV Exploded')
            },
            {
                value: ExportFormat.JSON,
                label: i18n.text('JSON')
            }
        ];
    }, [defaultFormat]);
    var entityTypes = useMemo(function () { return Object.keys(columnsByEntityType); }, [columnsByEntityType]);
    var entityTypesDetails = useMemo(function () {
        return entityTypes.reduce(function (acc, entityTypeUri) {
            var _a, _b, _c, _d, _e;
            var entityType = getEntityType(metadata, entityTypeUri);
            var attrCount = (_b = (_a = entityType.attributes) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
            var hiddenAttrCount = count(isHiddenAttribute, (_c = entityType.attributes) !== null && _c !== void 0 ? _c : []);
            var analyticsAttrCount = (_e = (_d = entityType.analyticsAttributes) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0;
            var totalAttrCount = attrCount + analyticsAttrCount + BASIC_ATTRIBUTES_COUNT;
            var columnsLength = pipe(prop(entityTypeUri), map(getFirstLevelSearchUri), uniq, length)(columnsByEntityType);
            var defaultCount = totalAttrCount - hiddenAttrCount - analyticsAttrCount;
            var selectedAttrCount = columnsLength > 0 ? columnsLength : defaultCount;
            acc[entityTypeUri] = {
                totalAttributesCount: totalAttrCount,
                selectedAttributesCount: selectedAttrCount,
                label: entityType === null || entityType === void 0 ? void 0 : entityType.label
            };
            return acc;
        }, {});
    }, [columnsByEntityType, entityTypes, metadata]);
    var handleChangeExportName = useCallback(function (e) {
        setExportName(e.target.value);
    }, []);
    var handleChangeFileFormat = useCallback(function (value) {
        setFileFormat(value);
    }, []);
    var handleChangeExportOvOnly = useCallback(function (_, checked) {
        setExportOvOnly(checked);
    }, []);
    var formatDateTime = useCallback(function (dateTime) {
        var date = dateTime
            .toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' })
            .replace(/\//g, '');
        var time = dateTime.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' });
        return "".concat(date, "_").concat(time);
    }, []);
    var defaultExportName = useMemo(function () { return i18n.text(DEFAULT_EXPORT_NAME); }, []);
    useEffect(function () {
        if (dialogOpen) {
            var now = new Date();
            var defaultName = "".concat(defaultExportName, " ").concat(formatDateTime(now));
            setExportName(defaultName);
            setFileFormat(defaultFormat);
            setExportOvOnly(false);
        }
    }, [dialogOpen, defaultFormat, formatDateTime, defaultExportName]);
    var handleExport = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
        var isCsv, baseOptions, tasks, typesWithSomeColumns, typesWithAllColumns, jobEntityTypes, options, results, failedJobs;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!exportName || !fileFormat)
                        return [2 /*return*/];
                    isCsv = [ExportFormat.CSVFlattened, ExportFormat.CSVExploded].includes(fileFormat.value);
                    baseOptions = __assign(__assign({ fileFormat: isCsv ? ExportDataFormat.CSV : ExportDataFormat.JSON, activeness: activityFilter, options: isSearchByOv ? 'parallelExecution,searchByOv' : 'parallelExecution' }, (fileFormat.value === ExportFormat.CSVExploded ? { exploded: true } : {})), (isCsv ? { dateFormat: 'readable' } : {}));
                    tasks = [];
                    typesWithSomeColumns = entityTypes.filter(function (uri) { return columnsByEntityType[uri].length > 0; });
                    typesWithAllColumns = entityTypes.filter(function (uri) { return columnsByEntityType[uri].length === 0; });
                    jobEntityTypes = [];
                    typesWithSomeColumns.forEach(function (entityTypeUri) {
                        var options = __assign(__assign({}, baseOptions), { select: columnsByEntityType[entityTypeUri].join(','), name: "".concat(exportName, "_").concat(entityTypesDetails[entityTypeUri].label) });
                        var headerOrder = isCsv ? ExportHeaderOrder.Select : ExportHeaderOrder.Default;
                        tasks.push(exportData({
                            exportPath: exportPath,
                            tenant: tenant,
                            options: options,
                            includeType: [entityTypeUri],
                            headerOrder: headerOrder,
                            filter: filter,
                            ovOnly: exportOvOnly
                        }));
                        jobEntityTypes.push([entityTypeUri]);
                    });
                    if (typesWithAllColumns.length > 0) {
                        options = __assign(__assign({}, baseOptions), { name: "".concat(exportName, "_entities"), sendHidden: false });
                        tasks.push(exportData({
                            exportPath: exportPath,
                            tenant: tenant,
                            options: options,
                            includeType: typesWithAllColumns,
                            headerOrder: ExportHeaderOrder.Default,
                            filter: filter,
                            ovOnly: exportOvOnly
                        }));
                        jobEntityTypes.push(typesWithAllColumns);
                    }
                    return [4 /*yield*/, promiseAllSettled(tasks)];
                case 1:
                    results = _a.sent();
                    failedJobs = results.flatMap(function (r, i) { return (r.status === 'rejected' ? jobEntityTypes[i] : []); });
                    return [2 /*return*/, {
                            failedJobs: failedJobs,
                            total: jobEntityTypes.flat().length
                        }];
            }
        });
    }); }, [
        exportName,
        fileFormat,
        filter,
        activityFilter,
        isSearchByOv,
        exportOvOnly,
        entityTypes,
        columnsByEntityType,
        entityTypesDetails,
        exportPath,
        tenant
    ]);
    return {
        exportName: exportName,
        onChangeExportName: handleChangeExportName,
        fileFormat: fileFormat,
        onChangeFileFormat: handleChangeFileFormat,
        formatOptions: formatOptions,
        entityTypesDetails: entityTypesDetails,
        exportOvOnly: exportOvOnly,
        onChangeExportOvOnly: handleChangeExportOvOnly,
        onExport: handleExport
    };
};
