"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpStrIns = void 0;
const AbstractOp_1 = require("./AbstractOp");
const json_pointer_1 = require("@jsonjoy.com/json-pointer");
const constants_1 = require("../constants");
/**
 * @category JSON Patch Extended
 */
class OpStrIns extends AbstractOp_1.AbstractOp {
    constructor(path, pos, str) {
        super(path);
        this.pos = pos;
        this.str = str;
    }
    op() {
        return 'str_ins';
    }
    code() {
        return constants_1.OPCODE.str_ins;
    }
    apply(doc) {
        const { val, key, obj } = (0, json_pointer_1.find)(doc, this.path);
        if (typeof val !== 'string') {
            if (val !== undefined)
                throw new Error('NOT_A_STRING');
            if (this.pos !== 0)
                throw new Error('POS');
        }
        const str = typeof val === 'string' ? val : '';
        const pos = Math.min(this.pos, str.length);
        const before = str.slice(0, pos);
        const after = str.slice(pos);
        const result = before + this.str + after;
        if (obj)
            obj[key] = result;
        else
            doc = result;
        return { doc, old: val };
    }
    toJson(parent) {
        const op = {
            op: 'str_ins',
            path: (0, json_pointer_1.formatJsonPointer)(this.path),
            pos: this.pos,
            str: this.str,
        };
        return op;
    }
    toCompact(parent, verbose) {
        const opcode = verbose ? 'str_ins' : constants_1.OPCODE.str_ins;
        return [opcode, this.path, this.pos, this.str];
    }
}
exports.OpStrIns = OpStrIns;
//# sourceMappingURL=OpStrIns.js.map