"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "SimpleKVStore", {
    enumerable: true,
    get: function() {
        return SimpleKVStore;
    }
});
const _env = require("@llamaindex/env");
const _FileSystem = require("../FileSystem.js");
const _constants = require("../constants.js");
const _types = require("./types.js");
class SimpleKVStore extends _types.BaseKVStore {
    data;
    persistPath;
    constructor(data = {}){
        super();
        this.data = data;
    }
    async put(key, val, collection = _constants.DEFAULT_COLLECTION) {
        if (!(collection in this.data)) {
            this.data[collection] = {};
        }
        this.data[collection][key] = structuredClone(val); // Creating a shallow copy of the object
        if (this.persistPath) {
            await this.persist(this.persistPath);
        }
    }
    async get(key, collection = _constants.DEFAULT_COLLECTION) {
        const collectionData = this.data[collection];
        if (collectionData == null) {
            return null;
        }
        if (!(key in collectionData)) {
            return null;
        }
        return structuredClone(collectionData[key]); // Creating a shallow copy of the object
    }
    async getAll(collection = _constants.DEFAULT_COLLECTION) {
        return structuredClone(this.data[collection]); // Creating a shallow copy of the object
    }
    async delete(key, collection = _constants.DEFAULT_COLLECTION) {
        if (key in this.data[collection]) {
            delete this.data[collection][key];
            if (this.persistPath) {
                await this.persist(this.persistPath);
            }
            return true;
        }
        return false;
    }
    async persist(persistPath) {
        // TODO: decide on a way to polyfill path
        const dirPath = _env.path.dirname(persistPath);
        if (!await (0, _FileSystem.exists)(dirPath)) {
            await _env.fs.mkdir(dirPath);
        }
        await _env.fs.writeFile(persistPath, JSON.stringify(this.data));
    }
    static async fromPersistPath(persistPath) {
        const dirPath = _env.path.dirname(persistPath);
        if (!await (0, _FileSystem.exists)(dirPath)) {
            await _env.fs.mkdir(dirPath);
        }
        let data = {};
        try {
            const fileData = await _env.fs.readFile(persistPath);
            data = JSON.parse(fileData.toString());
        } catch (e) {
            console.error(`No valid data found at path: ${persistPath} starting new store.`);
        }
        const store = new SimpleKVStore(data);
        store.persistPath = persistPath;
        return store;
    }
    toDict() {
        return this.data;
    }
    static fromDict(saveDict) {
        return new SimpleKVStore(saveDict);
    }
}
