"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toJsonOp = exports.jsonPatchOpToJsonOp = void 0;
const util_1 = require("@jsonjoy.com/json-expression/lib/util");
const tree_1 = require("./tree");
const util_2 = require("@jsonjoy.com/json-pointer/lib/util");
const jsonPatchOpToJsonOp = (operation) => {
    const op = operation.op;
    switch (op) {
        case 'test': {
            const value = (0, util_1.literal)(operation.value);
            const expression = [operation.not ? '!=' : '==', ['$', operation.path], value];
            return [[expression]];
        }
        case 'add': {
            return [[], [], [[0, operation.value]], [[0, (0, util_2.toPath)(operation.path)]]];
        }
        case 'remove': {
            const path = (0, util_2.toPath)(operation.path);
            return [[['$?', operation.path]], [[0, path]]];
        }
        case 'replace': {
            const path = (0, util_2.toPath)(operation.path);
            const test = path.length ? [['$?', operation.path]] : [];
            return [test, [[0, path]], [[1, operation.value]], [[1, path]]];
        }
        case 'move': {
            const path = (0, util_2.toPath)(operation.path);
            const from = (0, util_2.toPath)(operation.from);
            const test = from.length ? [['$?', operation.from]] : [];
            return [test, [[0, from]], [], [[0, path]]];
        }
        case 'copy': {
            const path = (0, util_2.toPath)(operation.path);
            const from = (0, util_2.toPath)(operation.from);
            return [
                [],
                [[0, from]],
                [],
                [
                    [0, from],
                    [0, path],
                ],
            ];
        }
    }
    return [[]];
};
exports.jsonPatchOpToJsonOp = jsonPatchOpToJsonOp;
const toJsonOp = (patch) => {
    const tree = tree_1.OpTree.from([[]]);
    for (const op of patch) {
        const otOp = (0, exports.jsonPatchOpToJsonOp)(op);
        // console.log(tree + '');
        const opTree = tree_1.OpTree.from(otOp);
        // console.log(opTree + '');
        tree.compose(opTree);
        // console.log(tree + '');
    }
    return tree.toJson();
};
exports.toJsonOp = toJsonOp;
//# sourceMappingURL=json-patch.js.map