"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonPatchStore = void 0;
const JsonPatch_1 = require("./JsonPatch");
const util_1 = require("@jsonjoy.com/json-pointer/lib/util");
class JsonPatchStore {
    constructor(model, path = [], base) {
        this.model = model;
        this.path = path;
        this.base = base;
        this.update = (change) => {
            const ops = Array.isArray(change) ? change : [change];
            this.patcher.apply(ops);
        };
        this.add = (path, value) => {
            const op = { op: 'add', path, value };
            this.update([op]);
            return op;
        };
        this.replace = (path, value) => {
            const op = { op: 'replace', path, value };
            this.update([op]);
            return op;
        };
        this.remove = (path) => {
            const op = { op: 'remove', path };
            this.update([op]);
            return op;
        };
        this.del = (path) => {
            try {
                return this.remove(path);
            }
            catch {
                return;
            }
        };
        this.get = (path = '') => this.patcher.get(path);
        this.getSnapshot = () => this.get();
        this.pfx = path.length ? path.join() : '';
        const api = model.api;
        this.patcher = new JsonPatch_1.JsonPatch(model, path, base);
        this.subscribe = (listener) => api.onChange.listen(listener);
    }
    bind(path) {
        return new JsonPatchStore(this.model, this.path.concat((0, util_1.toPath)(path)), this.base);
    }
    api() {
        try {
            return this.model.api.find(this.path);
        }
        catch {
            return;
        }
    }
}
exports.JsonPatchStore = JsonPatchStore;
//# sourceMappingURL=JsonPatchStore.js.map