"use strict";
/**
 * WorkbookWriter - Node.js Streaming Excel Writer
 *
 * Extends base with file path support and file system image loading.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkbookWriter = void 0;
const fs_1 = __importDefault(require("fs"));
const worksheet_writer_1 = require("./worksheet-writer.js");
const workbook_writer_browser_1 = require("./workbook-writer.browser.js");
const ooxml_paths_1 = require("../utils/ooxml-paths.js");
class WorkbookWriter extends workbook_writer_browser_1.WorkbookWriterBase {
    constructor(options = {}) {
        super(options, worksheet_writer_1.WorksheetWriter);
    }
    /**
     * Create output stream - supports filename option in Node.js
     */
    _createOutputStream(options) {
        if (options.filename) {
            return fs_1.default.createWriteStream(options.filename);
        }
        return super._createOutputStream(options);
    }
    /**
     * Add media files - supports loading from file system
     */
    addMedia() {
        return Promise.all(this.media.map(async (medium) => {
            if (medium.type === "image") {
                const filename = (0, ooxml_paths_1.mediaPath)(medium.name);
                // Node.js: support loading from file
                if (medium.filename) {
                    // `fs.readFile` returns a `Buffer` (which is already a `Uint8Array`).
                    // Avoid copying into a new `Uint8Array` for performance.
                    const data = await fs_1.default.promises.readFile(medium.filename);
                    this._addFile(data, filename);
                    return;
                }
                if (medium.buffer) {
                    this._addFile(medium.buffer, filename);
                    return;
                }
                if (medium.base64) {
                    const content = medium.base64.substring(medium.base64.indexOf(",") + 1);
                    this._addFile(content, filename, true);
                    return;
                }
            }
            throw new Error("Unsupported media");
        }));
    }
}
exports.WorkbookWriter = WorkbookWriter;
