import { ipcMain } from "electron";
import { WORKING_DIR } from "../constants";
import fs from 'fs/promises'
import path from 'path'

ipcMain.handle('fileStorage:writeFile', async (_, file: string, data: string | Buffer, inWorkingDir : boolean = true) => {
    const fullPath = path.join(inWorkingDir ? WORKING_DIR : '', file);
    await fs.mkdir(path.dirname(fullPath), { recursive: true });
    await fs.writeFile(fullPath, data);
    console.info("File written to " + fullPath);
    return true;
});

ipcMain.handle('fileStorage:readFile', async (_, file: string, inWorkingDir : boolean = true) => {
    try{
        const fullPath = path.join(inWorkingDir ? WORKING_DIR : '', file);
        const data = await fs.readFile(fullPath);
        return data;
    }catch(e){
        return null;
    }
});