"use strict";
/**
 * WorkbookReader - Node.js Streaming Workbook Reader
 *
 * Extends base with file path support and temp file storage for large files.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkbookReaderOptionsSchema = exports.WorkbookReader = void 0;
const fs_1 = __importDefault(require("fs"));
const os_1 = __importDefault(require("os"));
const path_1 = require("path");
const iterate_stream_1 = require("../utils/iterate-stream.js");
const worksheet_reader_1 = require("./worksheet-reader.js");
const hyperlink_reader_1 = require("./hyperlink-reader.js");
const workbook_reader_browser_1 = require("./workbook-reader.browser.js");
Object.defineProperty(exports, "WorkbookReaderOptionsSchema", { enumerable: true, get: function () { return workbook_reader_browser_1.WorkbookReaderOptionsSchema; } });
class WorkbookReader extends workbook_reader_browser_1.WorkbookReaderBase {
    constructor(input, options = {}) {
        super(input, options, worksheet_reader_1.WorksheetReader, hyperlink_reader_1.HyperlinkReader);
        this.input = input;
    }
    _getStream(input) {
        if (typeof input === "string") {
            return fs_1.default.createReadStream(input);
        }
        return super._getStream(input);
    }
    async _storeWaitingWorksheet(sheetNo, entry) {
        const tmpDir = fs_1.default.mkdtempSync((0, path_1.join)(os_1.default.tmpdir(), "excelts-"));
        const path = (0, path_1.join)(tmpDir, `sheet${sheetNo}.xml`);
        const cleanup = () => fs_1.default.rm(tmpDir, { recursive: true, force: true }, () => { });
        const writePromise = new Promise((resolve, reject) => {
            const tempStream = fs_1.default.createWriteStream(path);
            tempStream.on("error", reject);
            tempStream.on("finish", resolve);
            entry.pipe(tempStream);
        });
        return { sheetNo, path, cleanup, writePromise };
    }
    async *_processWaitingWorksheets(waitingWorksheets) {
        for (const ws of waitingWorksheets) {
            await ws.writePromise;
            const fileStream = fs_1.default.createReadStream(ws.path);
            try {
                yield* this._parseWorksheet((0, iterate_stream_1.iterateStream)(fileStream), ws.sheetNo);
            }
            finally {
                fileStream.close();
                ws.cleanup();
            }
        }
    }
}
exports.WorkbookReader = WorkbookReader;
