import fs from 'fs/promises'
import chalk from 'chalk'
import path from 'path'

export default class Database {
    logs

    constructor() {
        this.loadData()
    }

    async loadData() {
        const dbData = await fs.readFile(path.join(process.cwd(), 'db/db.json'), 'utf8');
        let dbJson;
        try {
            dbJson = JSON.parse(dbData);
        } catch {
            dbJson = []
        }
        this.logs = dbJson

        setInterval(() => {
            console.log("saving db")
            global.db.saveData()
        }, 5000)
    }

    async saveData() {
        let string = JSON.stringify(this.logs, null, 4)
        await fs.writeFile(path.join(process.cwd(), 'db/db.json'), string, "utf8");
    }
}