"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RawUpdater = void 0;
const cyia_code_util_1 = require("cyia-code-util");
class RawUpdater {
    static update(content, change) {
        change = change.sort((a, b) => b.start - a.start);
        return new RawUpdater(content, change).update();
    }
    constructor(content, changes) {
        this.content = content;
        this.changes = changes;
        this.originContent = content;
    }
    update() {
        this.changes.forEach((change) => {
            let deleteChange;
            let insertChange;
            if (change instanceof cyia_code_util_1.ReplaceChange) {
                insertChange = new cyia_code_util_1.InsertChange(change.start, change.content);
                deleteChange = new cyia_code_util_1.DeleteChange(change.start, change.length);
            }
            else if (change instanceof cyia_code_util_1.InsertChange) {
                insertChange = change;
            }
            else if (change instanceof cyia_code_util_1.DeleteChange) {
                deleteChange = change;
            }
            let list;
            if (deleteChange) {
                list = this.slice(deleteChange.start, deleteChange.length);
            }
            if (!list && insertChange) {
                list = this.slice(insertChange.start);
                list.splice(1, 0, insertChange.content);
            }
            else if (insertChange) {
                list.splice(1, 0, insertChange.content);
            }
            this.content = list.join('');
        });
        return this.content;
    }
    slice(pos, length = 0) {
        return [
            this.content.substring(0, pos),
            this.content.substring(pos + length),
        ];
    }
}
exports.RawUpdater = RawUpdater;
