const {ipcMain} = require('electron');
const path = require('path');
const dialog = require('./function/dialog');
const file = require('../../helper/file');

ipcMain.on('load-file-data', (event, arg) => {
    const data = {};
    const filepath = path.join(__dirname, '../data/');
    // Scan data folder
    const dataFiles = file.list(filepath);
    // Read all scanned files
    for (const elt of dataFiles) {
        const fileContent = file.read(filepath + elt);
        data[elt.replace('.json', '')] = JSON.parse(fileContent);
    }
    // Send data
    event.sender.send('file-data-loaded', data);
});

ipcMain.on('refresh-card', (event, arg) => {
    mainWindow.webContents.send('refresh-card');
});

ipcMain.on('confirm-delete', (event, arg) => {
    dialog.message(
        'Confirmation',
        `Voulez vous vraiment supprimer la note ${arg}`,
        'question',
        ['Non', 'Oui'],
        0,
        false,
        (index, btn) => {
            event.sender.send('delete-card', index === 1);
        }
    );
});

ipcMain.on('card-already-exist', (event, arg) => {
    dialog.error('Note éxistante', `Une note avec l'id ${arg} existe déjà, pour importer votre note veuillez d'abord la supprimer`);
});