"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpExtend = void 0;
const AbstractOp_1 = require("./AbstractOp");
const json_pointer_1 = require("@jsonjoy.com/json-pointer");
const constants_1 = require("../constants");
const { isArray } = Array;
/**
 * @category JSON Patch Extended
 */
class OpExtend extends AbstractOp_1.AbstractOp {
    constructor(path, props, deleteNull) {
        super(path);
        this.props = props;
        this.deleteNull = deleteNull;
    }
    op() {
        return 'extend';
    }
    code() {
        return constants_1.OPCODE.extend;
    }
    apply(doc) {
        const ref = (0, json_pointer_1.find)(doc, this.path);
        if ((0, json_pointer_1.isArrayReference)(ref)) {
            if (ref.val !== undefined) {
                ref.obj[ref.key] = this.extend(ref.val);
            }
        }
        else if ((0, json_pointer_1.isObjectReference)(ref)) {
            ref.obj[ref.key] = this.extend(ref.val);
        }
        else {
            doc = this.extend(doc);
        }
        return { doc };
    }
    extend(value) {
        if (isArray(value))
            return value;
        if (typeof value !== 'object')
            return value;
        if (!value)
            return value;
        for (const [key, v] of Object.entries(this.props)) {
            if (key === '__proto__')
                throw new Error('NO_PROTO');
            if (v === null && this.deleteNull) {
                delete value[key];
                continue;
            }
            value[key] = v;
        }
        return value;
    }
    toJson(parent) {
        const op = {
            op: 'extend',
            path: (0, json_pointer_1.formatJsonPointer)(this.path),
            props: this.props,
        };
        if (this.deleteNull)
            op.deleteNull = this.deleteNull;
        return op;
    }
    toCompact(parent, verbose) {
        const opcode = verbose ? 'extend' : constants_1.OPCODE.extend;
        return this.deleteNull ? [opcode, this.path, this.props, 1] : [opcode, this.path, this.props];
    }
}
exports.OpExtend = OpExtend;
//# sourceMappingURL=OpExtend.js.map