import { AbstractOp } from './AbstractOp';
import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { OPCODE } from '../constants';
/**
 * @category JSON Patch Extended
 */
export class OpStrIns extends AbstractOp {
    pos;
    str;
    constructor(path, pos, str) {
        super(path);
        this.pos = pos;
        this.str = str;
    }
    op() {
        return 'str_ins';
    }
    code() {
        return OPCODE.str_ins;
    }
    apply(doc) {
        const { val, key, obj } = 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: formatJsonPointer(this.path),
            pos: this.pos,
            str: this.str,
        };
        return op;
    }
    toCompact(parent, verbose) {
        const opcode = verbose ? 'str_ins' : OPCODE.str_ins;
        return [opcode, this.path, this.pos, this.str];
    }
}
//# sourceMappingURL=OpStrIns.js.map