import { AbstractOp } from './AbstractOp';
import { find, isArrayReference, isObjectReference, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { OPCODE } from '../constants';
const { isArray } = Array;
/**
 * @category JSON Patch Extended
 */
export class OpExtend extends AbstractOp {
    props;
    deleteNull;
    constructor(path, props, deleteNull) {
        super(path);
        this.props = props;
        this.deleteNull = deleteNull;
    }
    op() {
        return 'extend';
    }
    code() {
        return OPCODE.extend;
    }
    apply(doc) {
        const ref = find(doc, this.path);
        if (isArrayReference(ref)) {
            if (ref.val !== undefined) {
                ref.obj[ref.key] = this.extend(ref.val);
            }
        }
        else if (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: formatJsonPointer(this.path),
            props: this.props,
        };
        if (this.deleteNull)
            op.deleteNull = this.deleteNull;
        return op;
    }
    toCompact(parent, verbose) {
        const opcode = verbose ? 'extend' : OPCODE.extend;
        return this.deleteNull ? [opcode, this.path, this.props, 1] : [opcode, this.path, this.props];
    }
}
//# sourceMappingURL=OpExtend.js.map