"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpAdd = void 0;
const AbstractOp_1 = require("./AbstractOp");
const json_pointer_1 = require("@jsonjoy.com/json-pointer");
const constants_1 = require("../constants");
const clone_1 = require("@jsonjoy.com/util/lib/json-clone/clone");
/**
 * @category JSON Patch
 */
class OpAdd extends AbstractOp_1.AbstractOp {
    constructor(path, value) {
        super(path);
        this.value = value;
    }
    op() {
        return 'add';
    }
    code() {
        return constants_1.OPCODE.add;
    }
    apply(doc) {
        const { val, key, obj } = (0, json_pointer_1.find)(doc, this.path);
        const value = (0, clone_1.clone)(this.value);
        if (!obj)
            doc = value;
        else if (typeof key === 'string')
            obj[key] = value;
        else {
            const length = obj.length;
            if (key < length)
                obj.splice(key, 0, value);
            else if (key > length)
                throw new Error('INVALID_INDEX');
            else
                obj.push(value);
        }
        return { doc, old: val };
    }
    toJson(parent) {
        return {
            op: 'add',
            path: (0, json_pointer_1.formatJsonPointer)(this.path),
            value: this.value,
        };
    }
    toCompact(parent, verbose) {
        const opcode = verbose ? 'add' : constants_1.OPCODE.add;
        return [opcode, this.path, this.value];
    }
}
exports.OpAdd = OpAdd;
//# sourceMappingURL=OpAdd.js.map