"use strict";
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 __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 };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExportDialog = void 0;
var react_1 = __importStar(require("react"));
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var Dialog_1 = __importDefault(require("@mui/material/Dialog"));
var DialogTitle_1 = __importDefault(require("@mui/material/DialogTitle"));
var DialogActions_1 = __importDefault(require("@mui/material/DialogActions"));
var Button_1 = __importDefault(require("@mui/material/Button"));
var DialogContent_1 = __importDefault(require("@mui/material/DialogContent"));
var Typography_1 = __importDefault(require("@mui/material/Typography"));
var TextField_1 = __importDefault(require("@mui/material/TextField"));
var Checkbox_1 = __importDefault(require("@mui/material/Checkbox"));
var FormControlLabel_1 = __importDefault(require("@mui/material/FormControlLabel"));
var DropDownSelector_1 = require("../DropDownSelector");
var useInternalExport_1 = require("../hooks/useInternalExport");
var SnackbarContext_1 = require("../contexts/SnackbarContext");
var MdmModuleContext_1 = require("../contexts/MdmModuleContext");
var errors_1 = require("../helpers/errors");
var ErrorWrapper_1 = require("../ErrorWrapper");
var ExportDialog_module_css_1 = __importDefault(require("./ExportDialog.module.css"));
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 = (0, react_1.useContext)(SnackbarContext_1.SnackbarContext);
    var openConsoleApp = (0, MdmModuleContext_1.useMdmAction)('openConsoleApp');
    var isExportingRef = (0, react_1.useRef)(false);
    var _c = (0, useInternalExport_1.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, exportOvOnly = _c.exportOvOnly, onChangeExportOvOnly = _c.onChangeExportOvOnly;
    var handleConfirm = (0, react_1.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: ui_i18n_1.default.text("Your export job is underway. We'll send an email with the download link once it's complete."),
                                action: {
                                    label: ui_i18n_1.default.text('View progress'),
                                    onClick: function () {
                                        openConsoleApp('Export');
                                    }
                                }
                            });
                        }
                        if (failedCount > 0) {
                            failedJobsString = (_b = result.failedJobs) === null || _b === void 0 ? void 0 : _b.join(', ');
                            errorMessage = ui_i18n_1.default.text('Failed to export ${failedJobsString}.', { failedJobsString: failedJobsString });
                            error = new Error(errorMessage);
                            (0, errors_1.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 = (0, react_1.useCallback)(function () {
        onClose();
        onExternalExport(exportOvOnly);
    }, [onExternalExport, onClose, exportOvOnly]);
    var renderDetails = (0, react_1.useMemo)(function () { return (react_1.default.createElement(react_1.default.Fragment, null, Object.values(entityTypesDetails).map(function (data, index) { return (react_1.default.createElement("span", { key: index },
        react_1.default.createElement("span", { className: ExportDialog_module_css_1.default.attributesCount }, data.label),
        ui_i18n_1.default.text('(${selected}/${total} attributes)', {
            selected: data.selectedAttributesCount,
            total: data.totalAttributesCount
        }),
        index < Object.values(entityTypesDetails).length - 1 && ', ')); }))); }, [entityTypesDetails]);
    return (react_1.default.createElement(Dialog_1.default, { open: open, onClose: onClose, fullWidth: true, classes: { paper: ExportDialog_module_css_1.default.dialog } },
        react_1.default.createElement(DialogTitle_1.default, { classes: { root: ExportDialog_module_css_1.default.dialogTitle } }, ui_i18n_1.default.text('Export')),
        react_1.default.createElement(DialogContent_1.default, { classes: { root: ExportDialog_module_css_1.default.dialogContent } },
            react_1.default.createElement(ErrorWrapper_1.ErrorWrapper, { errorMessage: exportName ? '' : ui_i18n_1.default.text('This field is required') },
                react_1.default.createElement(TextField_1.default, { label: ui_i18n_1.default.text('Name your export'), value: exportName, onChange: onChangeExportName, variant: 'filled', fullWidth: true, size: 'small', required: true })),
            react_1.default.createElement(Typography_1.default, { variant: "subtitle2", className: ExportDialog_module_css_1.default.subtitle }, ui_i18n_1.default.text('Data selected')),
            react_1.default.createElement("div", { className: ExportDialog_module_css_1.default.summary },
                react_1.default.createElement(Typography_1.default, { className: ExportDialog_module_css_1.default.totalCaption, color: "textSecondary" },
                    react_1.default.createElement("span", { className: ExportDialog_module_css_1.default.totalNumber }, ui_i18n_1.default.number(profilesCount, '0,0')),
                    profilesCount === 1 ? ui_i18n_1.default.text('Profile') : ui_i18n_1.default.text('Profiles')),
                react_1.default.createElement(Typography_1.default, { variant: "body2", color: "textSecondary" }, renderDetails)),
            react_1.default.createElement(Typography_1.default, { variant: "subtitle2", className: ExportDialog_module_css_1.default.subtitle }, ui_i18n_1.default.text('Export options')),
            react_1.default.createElement(DropDownSelector_1.DropDownSelector, { height: 44, value: fileFormat, onChange: onChangeFileFormat, label: ui_i18n_1.default.text('File format'), options: formatOptions }),
            react_1.default.createElement("div", { className: ExportDialog_module_css_1.default.exportOvOnlyWrapper },
                react_1.default.createElement(FormControlLabel_1.default, { className: ExportDialog_module_css_1.default.exportOvOnlyLabel, control: react_1.default.createElement(Checkbox_1.default, { checked: exportOvOnly, onChange: onChangeExportOvOnly, color: "primary", size: "small" }), label: react_1.default.createElement(Typography_1.default, { variant: "body2" }, ui_i18n_1.default.text('Export Operational Values (OV) only')) }),
                react_1.default.createElement(Typography_1.default, { variant: "body2", color: "textSecondary", className: ExportDialog_module_css_1.default.exportOvOnlyHelper }, ui_i18n_1.default.text('Only those attribute values that are selected by the survivorship rules will be exported'))),
            react_1.default.createElement("div", { className: ExportDialog_module_css_1.default.externalExportWrapper },
                react_1.default.createElement(Typography_1.default, { component: "span", variant: "body2" }, ui_i18n_1.default.text('Want more export options?')),
                react_1.default.createElement(Button_1.default, { onClick: handleExternalExport, color: "primary" }, ui_i18n_1.default.text('Go to export application')))),
        react_1.default.createElement(DialogActions_1.default, { classes: { root: ExportDialog_module_css_1.default.dialogActions } },
            react_1.default.createElement(Button_1.default, { onClick: onClose }, ui_i18n_1.default.text('Cancel')),
            react_1.default.createElement(Button_1.default, { onClick: handleConfirm, color: "primary", disabled: !exportName }, ui_i18n_1.default.text('Export')))));
};
exports.ExportDialog = ExportDialog;
