const { ipcMain, dialog, app, shell } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');

const configPath = path.join(app.getPath('userData'), 'config.json');

function readConfig() {
  try { return JSON.parse(fs.readFileSync(configPath, 'utf8')); } catch { return {}; }
}
function writeConfig(data) {
  try { fs.writeFileSync(configPath, JSON.stringify(data, null, 2)); } catch {}
}

function register(mainWindow) {
  ipcMain.handle('select-folder', async () => {
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory'],
      title: '이미지 폴더 선택',
    });
    if (result.canceled) return null;
    return result.filePaths[0];
  });

  ipcMain.handle('get-home-dir', () => os.homedir());

  ipcMain.handle('get-last-folder', () => {
    const cfg = readConfig();
    if (cfg.lastFolder) {
      try { fs.accessSync(cfg.lastFolder); return cfg.lastFolder; } catch {}
    }
    return null;
  });

  ipcMain.handle('set-last-folder', (_e, folderPath) => {
    const cfg = readConfig();
    cfg.lastFolder = folderPath;
    writeConfig(cfg);
  });

  ipcMain.handle('list-directories', (_e, folderPath) => {
    try {
      const entries = fs.readdirSync(folderPath, { withFileTypes: true });
      return entries
        .filter(e => e.isDirectory() && !e.name.startsWith('.'))
        .map(e => {
          const fullPath = path.join(folderPath, e.name);
          let hasChildren = false;
          try {
            hasChildren = fs.readdirSync(fullPath, { withFileTypes: true })
              .some(c => c.isDirectory() && !c.name.startsWith('.'));
          } catch {}
          return { name: e.name, path: fullPath, hasChildren };
        })
        .sort((a, b) => a.name.localeCompare(b.name));
    } catch { return null; }
  });

  ipcMain.handle('reveal-folder', (_e, folderPath) => shell.openPath(folderPath));

  ipcMain.handle('get-preview-on', () => {
    const cfg = readConfig();
    return cfg.previewOn !== false; // 기본값 true
  });

  ipcMain.handle('set-preview-on', (_e, on) => {
    const cfg = readConfig();
    cfg.previewOn = on;
    writeConfig(cfg);
  });
}

module.exports = { register };