/**
 * HyperlinkReader - Streaming Hyperlink Reader
 *
 * Cross-platform implementation.
 */
import { EventEmitter } from "../../stream/index.js";
import { parseSax } from "../utils/parse-sax.js";
import { Enums } from "../enums.js";
import { RelType } from "../xlsx/rel-type.js";
class HyperlinkReader extends EventEmitter {
    constructor({ workbook, id, iterator, options }) {
        super();
        this._hyperlinkCount = 0;
        this.workbook = workbook;
        this.id = id;
        this.iterator = iterator;
        this.options = options;
    }
    get count() {
        return this.hyperlinks ? this._hyperlinkCount : 0;
    }
    each(fn) {
        const hyperlinks = this.hyperlinks;
        if (!hyperlinks) {
            return;
        }
        for (const rId in hyperlinks) {
            fn(hyperlinks[rId], rId);
        }
    }
    async read() {
        const { iterator } = this;
        const hyperlinkMode = this.options.hyperlinks;
        const emitHyperlinks = hyperlinkMode === "emit";
        const cacheHyperlinks = hyperlinkMode === "cache";
        let cachedHyperlinks = null;
        if (cacheHyperlinks) {
            this._hyperlinkCount = 0;
            this.hyperlinks = cachedHyperlinks = Object.create(null);
        }
        if (!emitHyperlinks && !cacheHyperlinks) {
            this.emit("finished");
            return;
        }
        try {
            for await (const events of parseSax(iterator)) {
                for (const { eventType, value } of events) {
                    if (eventType !== "opentag") {
                        continue;
                    }
                    const node = value;
                    if (node.name !== "Relationship") {
                        continue;
                    }
                    const attributes = node.attributes;
                    if (attributes.Type !== RelType.Hyperlink) {
                        continue;
                    }
                    const relationship = {
                        type: Enums.RelationshipType.Hyperlink,
                        rId: attributes.Id,
                        target: attributes.Target,
                        targetMode: attributes.TargetMode
                    };
                    if (emitHyperlinks) {
                        this.emit("hyperlink", relationship);
                        continue;
                    }
                    // cache mode
                    const rId = relationship.rId;
                    if (cachedHyperlinks && cachedHyperlinks[rId] === undefined) {
                        this._hyperlinkCount += 1;
                    }
                    cachedHyperlinks[rId] = relationship;
                }
            }
            this.emit("finished");
        }
        catch (error) {
            this.emit("error", error);
        }
    }
}
export { HyperlinkReader };
