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 React, { useCallback, useContext, useMemo, useRef } from 'react';
import i18n from 'ui-i18n';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import DialogContent from '@mui/material/DialogContent';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import { DropDownSelector } from '../DropDownSelector';
import { useInternalExport } from '../hooks/useInternalExport';
import { SnackbarContext } from '../contexts/SnackbarContext';
import { useMdmAction } from '../contexts/MdmModuleContext';
import { showErrorMessage } from '../helpers/errors';
import { ErrorWrapper } from '../ErrorWrapper';
import styles from './ExportDialog.module.css';
export var ExportDialog = function (_a) {
    var open = _a.open, onClose = _a.onClose, columnsByEntityType = _a.columnsByEntityType, profilesCount = _a.profilesCount, onExternalExport = _a.onExternalExport, onLoadingChange = _a.onLoadingChange, _b = _a.filter, filter = _b === void 0 ? '' : _b, activityFilter = _a.activityFilter, isSearchByOv = _a.isSearchByOv;
    var showSnackbarMessage = useContext(SnackbarContext);
    var openConsoleApp = useMdmAction('openConsoleApp');
    var isExportingRef = useRef(false);
    var _c = useInternalExport({
        columnsByEntityType: columnsByEntityType,
        dialogOpen: open,
        filter: filter,
        activityFilter: activityFilter,
        isSearchByOv: isSearchByOv
    }), exportName = _c.exportName, onChangeExportName = _c.onChangeExportName, fileFormat = _c.fileFormat, onChangeFileFormat = _c.onChangeFileFormat, formatOptions = _c.formatOptions, onExport = _c.onExport, entityTypesDetails = _c.entityTypesDetails;
    var handleConfirm = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
        var result, failedCount, successfulCount, failedJobsString, errorMessage, error;
        var _a, _b;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    if (isExportingRef.current)
                        return [2 /*return*/];
                    isExportingRef.current = true;
                    onLoadingChange === null || onLoadingChange === void 0 ? void 0 : onLoadingChange(true);
                    onClose();
                    _c.label = 1;
                case 1:
                    _c.trys.push([1, , 3, 4]);
                    return [4 /*yield*/, onExport()];
                case 2:
                    result = _c.sent();
                    if (result) {
                        failedCount = ((_a = result.failedJobs) === null || _a === void 0 ? void 0 : _a.length) || 0;
                        successfulCount = result.total - failedCount;
                        if (successfulCount > 0) {
                            showSnackbarMessage({
                                message: i18n.text("Your export job is underway. We'll send an email with the download link once it's complete."),
                                action: {
                                    label: i18n.text('View progress'),
                                    onClick: function () {
                                        openConsoleApp('Export');
                                    }
                                }
                            });
                        }
                        if (failedCount > 0) {
                            failedJobsString = (_b = result.failedJobs) === null || _b === void 0 ? void 0 : _b.join(', ');
                            errorMessage = i18n.text('Failed to export ${failedJobsString}.', { failedJobsString: failedJobsString });
                            error = new Error(errorMessage);
                            showErrorMessage(error, {
                                message: errorMessage
                            });
                        }
                    }
                    return [3 /*break*/, 4];
                case 3:
                    isExportingRef.current = false;
                    onLoadingChange === null || onLoadingChange === void 0 ? void 0 : onLoadingChange(false);
                    return [7 /*endfinally*/];
                case 4: return [2 /*return*/];
            }
        });
    }); }, [onClose, onExport, showSnackbarMessage, openConsoleApp, onLoadingChange]);
    var handleExternalExport = useCallback(function () {
        onClose();
        onExternalExport();
    }, [onExternalExport, onClose]);
    var renderDetails = useMemo(function () { return (React.createElement(React.Fragment, null, Object.values(entityTypesDetails).map(function (data, index) { return (React.createElement("span", { key: index },
        React.createElement("span", { className: styles.attributesCount }, data.label),
        i18n.text('(${selected}/${total} attributes)', {
            selected: data.selectedAttributesCount,
            total: data.totalAttributesCount
        }),
        index < Object.values(entityTypesDetails).length - 1 && ', ')); }))); }, [entityTypesDetails]);
    return (React.createElement(Dialog, { open: open, onClose: onClose, fullWidth: true, classes: { paper: styles.dialog } },
        React.createElement(DialogTitle, { classes: { root: styles.dialogTitle } }, i18n.text('Export')),
        React.createElement(DialogContent, { classes: { root: styles.dialogContent } },
            React.createElement(ErrorWrapper, { errorMessage: exportName ? '' : i18n.text('This field is required') },
                React.createElement(TextField, { label: i18n.text('Name your export'), value: exportName, onChange: onChangeExportName, variant: 'filled', fullWidth: true, size: 'small', required: true })),
            React.createElement(Typography, { variant: "subtitle2", className: styles.subtitle }, i18n.text('Data selected')),
            React.createElement("div", { className: styles.summary },
                React.createElement(Typography, { className: styles.totalCaption, color: "textSecondary" },
                    React.createElement("span", { className: styles.totalNumber }, i18n.number(profilesCount, '0,0')),
                    profilesCount === 1 ? i18n.text('Profile') : i18n.text('Profiles')),
                React.createElement(Typography, { variant: "body2", color: "textSecondary" }, renderDetails)),
            React.createElement(Typography, { variant: "subtitle2", className: styles.subtitle }, i18n.text('Export options')),
            React.createElement(DropDownSelector, { height: 44, value: fileFormat, onChange: onChangeFileFormat, label: i18n.text('File format'), options: formatOptions }),
            React.createElement("div", { className: styles.externalExportWrapper },
                React.createElement(Typography, { component: "span", variant: "body2" }, i18n.text('Want more export options?')),
                React.createElement(Button, { onClick: handleExternalExport, color: "primary" }, i18n.text('Go to export application')))),
        React.createElement(DialogActions, { classes: { root: styles.dialogActions } },
            React.createElement(Button, { onClick: onClose }, i18n.text('Cancel')),
            React.createElement(Button, { onClick: handleConfirm, color: "primary", disabled: !exportName }, i18n.text('Export')))));
};
