/**
 * DevExtreme (esm/ui/pivot_grid/ui.pivot_grid.export.js)
 * Version: 22.1.7 (build 23032-0308)
 * Build date: Wed Feb 01 2023
 *
 * Copyright (c) 2012 - 2023 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
import _extends from "@babel/runtime/helpers/esm/extends";
import Class from "../../core/class";
import {
    isDefined
} from "../../core/utils/type";
import {
    extend
} from "../../core/utils/extend";
import {
    each
} from "../../core/utils/iterator";
import {
    hasWindow
} from "../../core/utils/window";
import {
    getDefaultAlignment
} from "../../core/utils/position";
import formatHelper from "../../format_helper";
import localizationNumber from "../../localization/number";
import {
    excel as excelExporter,
    export as exportMethod
} from "../../exporter";
import {
    prepareItems
} from "../grid_core/ui.grid_core.export";
import {
    when,
    Deferred
} from "../../core/utils/deferred";
var DEFAULT_DATA_TYPE = "string";
var DEFAUL_COLUMN_WIDTH = 100;
export var ExportController = {
    exportToExcel: function() {
        exportMethod(this.getDataProvider(), {
            fileName: this.option("export.fileName"),
            proxyUrl: this.option("export.proxyUrl"),
            format: "EXCEL",
            rtlEnabled: this.option("rtlEnabled"),
            ignoreErrors: this.option("export.ignoreExcelErrors"),
            exportingAction: this._actions.onExporting,
            exportedAction: this._actions.onExported,
            fileSavingAction: this._actions.onFileSaving
        }, excelExporter.getData)
    },
    _getLength: function(items) {
        var i;
        var itemCount = items[0].length;
        var cellCount = 0;
        for (i = 0; i < itemCount; i++) {
            cellCount += items[0][i].colspan || 1
        }
        return cellCount
    },
    _correctCellsInfoItemLengths: function(cellsInfo, expectedLength) {
        for (var i = 0; i < cellsInfo.length; i++) {
            while (cellsInfo[i].length < expectedLength) {
                cellsInfo[i].push({})
            }
        }
        return cellsInfo
    },
    _calculateCellInfoItemLength: function(columnsRow) {
        var result = 0;
        for (var columnIndex = 0; columnIndex < columnsRow.length; columnIndex++) {
            result += isDefined(columnsRow[columnIndex].colspan) ? columnsRow[columnIndex].colspan : 1
        }
        return result
    },
    _getEmptyCell: function() {
        return {
            text: "",
            value: void 0,
            colspan: 1,
            rowspan: 1
        }
    },
    _getAllItems: function(columnsInfo, rowsInfoItems, cellsInfo) {
        var cellIndex;
        var rowIndex;
        var correctedCellsInfo = cellsInfo;
        var rowsLength = this._getLength(rowsInfoItems);
        var headerRowsCount = columnsInfo.length;
        if (columnsInfo.length > 0 && columnsInfo[0].length > 0 && cellsInfo.length > 0 && 0 === cellsInfo[0].length) {
            var cellInfoItemLength = this._calculateCellInfoItemLength(columnsInfo[0]);
            if (cellInfoItemLength > 0) {
                correctedCellsInfo = this._correctCellsInfoItemLengths(cellsInfo, cellInfoItemLength)
            }
        }
        var sourceItems = columnsInfo.concat(correctedCellsInfo);
        for (rowIndex = 0; rowIndex < rowsInfoItems.length; rowIndex++) {
            for (cellIndex = rowsInfoItems[rowIndex].length - 1; cellIndex >= 0; cellIndex--) {
                if (!isDefined(sourceItems[rowIndex + headerRowsCount])) {
                    sourceItems[rowIndex + headerRowsCount] = []
                }
                sourceItems[rowIndex + headerRowsCount].splice(0, 0, extend({}, rowsInfoItems[rowIndex][cellIndex]))
            }
        }
        sourceItems[0].splice(0, 0, extend({}, this._getEmptyCell(), {
            alignment: getDefaultAlignment(this._options.rtlEnabled),
            colspan: rowsLength,
            rowspan: headerRowsCount
        }));
        return prepareItems(sourceItems, this._getEmptyCell())
    },
    getDataProvider: function() {
        return new DataProvider(this)
    }
};
export var DataProvider = Class.inherit({
    ctor: function(exportController) {
        this._exportController = exportController
    },
    ready: function() {
        this._initOptions();
        var options = this._options;
        return when(options.items).done(items => {
            var headerSize = items[0][0].rowspan;
            var columns = items[headerSize - 1];
            each(columns, (columnIndex, column) => {
                column.width = DEFAUL_COLUMN_WIDTH
            });
            options.columns = columns;
            options.items = items
        })
    },
    _initOptions: function() {
        var exportController = this._exportController;
        var dataController = exportController._dataController;
        var items = new Deferred;
        dataController.beginLoading();
        setTimeout((function() {
            var columnsInfo = extend(true, [], dataController.getColumnsInfo(true));
            var rowsInfoItems = extend(true, [], dataController.getRowsInfo(true));
            var cellsInfo = dataController.getCellsInfo(true);
            items.resolve(exportController._getAllItems(columnsInfo, rowsInfoItems, cellsInfo));
            dataController.endLoading()
        }));
        this._options = {
            items: items,
            rtlEnabled: exportController.option("rtlEnabled"),
            dataFields: exportController.getDataSource().getAreaFields("data"),
            customizeExcelCell: exportController.option("export.customizeExcelCell"),
            rowsArea: exportController._rowsArea,
            columnsArea: exportController._columnsArea
        }
    },
    getColumns: function() {
        return this._options.columns
    },
    getColumnsWidths: function() {
        var colsArea = this._options.columnsArea;
        var rowsArea = this._options.rowsArea;
        var columns = this._options.columns;
        var useDefaultWidth = !hasWindow() || "virtual" === colsArea.option("scrolling.mode") || colsArea.element().is(":hidden");
        return useDefaultWidth ? columns.map(_ => DEFAUL_COLUMN_WIDTH) : rowsArea.getColumnsWidth().concat(colsArea.getColumnsWidth())
    },
    getRowsCount: function() {
        return this._options.items.length
    },
    getGroupLevel: function() {
        return 0
    },
    getCellMerging: function(rowIndex, cellIndex) {
        var items = this._options.items;
        var item = items[rowIndex] && items[rowIndex][cellIndex];
        return item ? {
            colspan: item.colspan - 1,
            rowspan: item.rowspan - 1
        } : {
            colspan: 0,
            rowspan: 0
        }
    },
    getFrozenArea: function() {
        return {
            x: this.getRowAreaColCount(),
            y: this.getColumnAreaRowCount()
        }
    },
    getCellType: function(rowIndex, cellIndex) {
        var style = this.getStyles()[this.getStyleId(rowIndex, cellIndex)];
        return style && style.dataType || "string"
    },
    getCellData: function(rowIndex, cellIndex, isExcelJS) {
        var result = {};
        var items = this._options.items;
        var item = items[rowIndex] && items[rowIndex][cellIndex] || {};
        if (isExcelJS) {
            result.cellSourceData = item;
            var areaName = this._tryGetAreaName(item, rowIndex, cellIndex);
            if (areaName) {
                result.cellSourceData.area = areaName
            }
            result.cellSourceData.rowIndex = rowIndex;
            result.cellSourceData.columnIndex = cellIndex
        }
        if ("string" === this.getCellType(rowIndex, cellIndex)) {
            result.value = item.text
        } else {
            result.value = item.value
        }
        if (result.cellSourceData && result.cellSourceData.isWhiteSpace) {
            result.value = ""
        }
        return result
    },
    _tryGetAreaName(item, rowIndex, cellIndex) {
        if (this.isColumnAreaCell(rowIndex, cellIndex)) {
            return "column"
        } else if (this.isRowAreaCell(rowIndex, cellIndex)) {
            return "row"
        } else if (isDefined(item.dataIndex)) {
            return "data"
        }
    },
    isRowAreaCell(rowIndex, cellIndex) {
        return rowIndex >= this.getColumnAreaRowCount() && cellIndex < this.getRowAreaColCount()
    },
    isColumnAreaCell(rowIndex, cellIndex) {
        return cellIndex >= this.getRowAreaColCount() && rowIndex < this.getColumnAreaRowCount()
    },
    getColumnAreaRowCount() {
        return this._options.items[0][0].rowspan
    },
    getRowAreaColCount() {
        return this._options.items[0][0].colspan
    },
    getHeaderStyles() {
        return [{
            alignment: "center",
            dataType: "string"
        }, {
            alignment: getDefaultAlignment(this._options.rtlEnabled),
            dataType: "string"
        }]
    },
    getDataFieldStyles() {
        var dataFields = this._options.dataFields;
        var dataItemStyle = {
            alignment: this._options.rtlEnabled ? "left" : "right"
        };
        var dataFieldStyles = [];
        if (dataFields.length) {
            dataFields.forEach(dataField => {
                dataFieldStyles.push(_extends({}, dataItemStyle, {
                    format: dataField.format,
                    dataType: this.getCellDataType(dataField)
                }))
            });
            return dataFieldStyles
        }
        return [dataItemStyle]
    },
    getStyles: function() {
        if (this._styles) {
            return this._styles
        }
        this._styles = [...this.getHeaderStyles(), ...this.getDataFieldStyles()];
        return this._styles
    },
    getCellDataType: function(field) {
        if (field && field.customizeText) {
            return "string"
        }
        if (field.dataType) {
            return field.dataType
        }
        if (field.format) {
            if (1 === localizationNumber.parse(formatHelper.format(1, field.format))) {
                return "number"
            }
            if (formatHelper.format(new Date, field.format)) {
                return "date"
            }
        }
        return DEFAULT_DATA_TYPE
    },
    getStyleId: function(rowIndex, cellIndex) {
        var items = this._options.items;
        var item = items[rowIndex] && items[rowIndex][cellIndex] || {};
        if (0 === cellIndex && 0 === rowIndex || this.isColumnAreaCell(rowIndex, cellIndex)) {
            return 0
        } else if (this.isRowAreaCell(rowIndex, cellIndex)) {
            return 1
        }
        return this.getHeaderStyles().length + (item.dataIndex || 0)
    },
    hasCustomizeExcelCell: function() {
        return isDefined(this._options.customizeExcelCell)
    },
    customizeExcelCell: function(e) {
        if (this._options.customizeExcelCell) {
            this._options.customizeExcelCell(e)
        }
    }
});
