import { handlePaginationExport } from "../util/pagination";

const newLine = "\r\n", separator = ",";

export function exportVTableToCsv(tableInstance, option) {
    const exportAllData = !!(null == option ? void 0 : option.exportAllData), {handleRowCount: handleRowCount, reset: reset} = handlePaginationExport(tableInstance, exportAllData), maxRow = handleRowCount(), maxCol = tableInstance.colCount - 1;
    let copyValue = "";
    for (let row = 0; row <= maxRow; row++) {
        for (let col = 0; col <= maxCol; col++) {
            const copyCellValue = getCopyCellValue(col, row, tableInstance, option);
            if ("undefined" != typeof Promise && copyCellValue instanceof Promise) ; else {
                const strCellValue = `${void 0 === copyCellValue ? "" : copyCellValue}`;
                /^\[object .*\]$/.exec(strCellValue) || (copyValue += strCellValue);
            }
            col !== maxCol && (copyValue += ",");
        }
        copyValue += "\r\n";
    }
    return reset(), copyValue;
}

function getCopyCellValue(col, row, tableInstance, option) {
    var _a;
    const rawRecord = tableInstance.getCellRawRecord(col, row), cellValue = null !== (_a = rawRecord && rawRecord.vtableMergeName) && void 0 !== _a ? _a : tableInstance.getCellValue(col, row, !1);
    if (null == option ? void 0 : option.formatExportOutput) {
        const cellInfo = {
            cellType: tableInstance.getCellType(col, row),
            cellValue: cellValue,
            table: tableInstance,
            col: col,
            row: row
        }, formattedValue = option.formatExportOutput(cellInfo);
        if (void 0 !== formattedValue) return "string" == typeof formattedValue ? '"' + formattedValue + '"' : formattedValue;
    }
    const cellRange = tableInstance.getCellRange(col, row), copyStartCol = cellRange.start.col, copyStartRow = cellRange.start.row;
    if (copyStartCol !== col || copyStartRow !== row) return "";
    let value = cellValue;
    return !1 !== (null == option ? void 0 : option.escape) ? value = escapeForCSV(value) : "string" == typeof value && (value = '"' + value + '"'), 
    value;
}

function escapeForCSV(str) {
    if ("string" != typeof str) return str;
    let escapedStr = str.replace(/"/g, '""');
    return /[,"\r\n]/.test(escapedStr) && (escapedStr = `"${escapedStr}"`), escapedStr;
}
//# sourceMappingURL=index.js.map
