"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuillDeltaNode = void 0;
const isEmpty_1 = require("@jsonjoy.com/util/lib/isEmpty");
const deepEqual_1 = require("@jsonjoy.com/util/lib/json-equal/deepEqual");
const peritext_1 = require("../peritext");
const constants_1 = require("../constants");
const constants_2 = require("./constants");
const ExtNode_1 = require("../../json-crdt/extensions/ExtNode");
const util_1 = require("./util");
const hash_1 = require("../../json-crdt/hash");
class QuillDeltaNode extends ExtNode_1.ExtNode {
    constructor(data) {
        super(data);
        this.data = data;
        // ------------------------------------------------------------------ ExtNode
        this.extId = constants_1.ExtensionId.quill;
        this._view = [];
        this._viewHash = -1;
        this.txt = new peritext_1.Peritext(data.doc, this.text(), this.slices());
    }
    text() {
        return this.data.get(0);
    }
    slices() {
        return this.data.get(1);
    }
    name() {
        return constants_2.MNEMONIC;
    }
    view() {
        const overlay = this.txt.overlay;
        const hash = (0, hash_1.updateRga)(overlay.refresh(true), this.txt.str);
        if (hash === this._viewHash)
            return this._view;
        const ops = [];
        let chunk;
        const nextTuple = overlay.tuples0(undefined);
        let tuple;
        while ((tuple = nextTuple())) {
            const [p1, p2] = tuple;
            const attributes = (0, util_1.getAttributes)(p1);
            let insert = '';
            chunk = overlay.chunkSlices0(chunk, p1, p2, (chunk, off, len) => {
                const data = chunk.data;
                if (data)
                    insert += data.slice(off, off + len);
            });
            if (insert) {
                if (insert === constants_2.QuillConst.EmbedChar && attributes && attributes[constants_2.QuillConst.EmbedSliceType]) {
                    const op = { insert: attributes[constants_2.QuillConst.EmbedSliceType] };
                    delete attributes[constants_2.QuillConst.EmbedSliceType];
                    if (!(0, isEmpty_1.isEmpty)(attributes))
                        op.attributes = attributes;
                    ops.push(op);
                    continue;
                }
                else {
                    const lastOp = ops[ops.length - 1];
                    if (lastOp && typeof lastOp.insert === 'string' && (0, deepEqual_1.deepEqual)(lastOp.attributes, attributes)) {
                        lastOp.insert += insert;
                        continue;
                    }
                }
                const op = { insert };
                if (attributes)
                    op.attributes = attributes;
                ops.push(op);
            }
        }
        this._viewHash = hash;
        this._view = ops;
        return ops;
    }
}
exports.QuillDeltaNode = QuillDeltaNode;
//# sourceMappingURL=QuillDeltaNode.js.map