const { contextBridge, ipcRenderer } = require('electron');
const fs = require('fs');
const path = require('path');
const os = require('os');

contextBridge.exposeInMainWorld('electronAPI', {
  minimize: () => ipcRenderer.send('window-minimize'),
  maximize: () => ipcRenderer.send('window-maximize'),
  close: () => ipcRenderer.send('window-close'),
  openChildWindow: (data) => ipcRenderer.send('open-child-window', data),

  onSetUrl: (callback) => ipcRenderer.on('set-url', (event, data) => callback(data)),

  getMessageUrl: () => 'http://busyuka.mydns.jp:6500/FFXI/launcher/message.json',

  getUserDataPath: () => path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと'),

  saveFile: (filePath, content) => {
    try {
      const dir = path.dirname(filePath);
      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(filePath, content, 'utf8');
    } catch (e) {
      console.error('[saveFile] ファイル保存エラー:', e);
    }
  },

  readJsonFile: (filePath) => {
    try {
      return JSON.parse(fs.readFileSync(filePath, 'utf8'));
    } catch {
      return null;
    }
  },

  getSettings: () => {
    try {
      const settingsPath = path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと', 'settings.json');
      return JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    } catch {
      return {};
    }
  },

  playButtonVoice: (filename) => {
    try {
      const setting = JSON.parse(fs.readFileSync(
        path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと', 'settings.json'),
        'utf8'
      ));
      if (setting.voice === false) return;
    } catch {}
    ipcRenderer.send('play-button-voice', filename);
  },

  playGreeting: (zone) => {
    ipcRenderer.send('play-greeting', zone);
  },

  sayByeByeMofu: () => {
    ipcRenderer.send('say-bye');
  },

  onSayBye: (callback) => {
    ipcRenderer.on('say-bye', () => callback());
  },
  
  saveSettings: (settings) => {
    try {
      const dir = path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと');
      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(settings, null, 2), 'utf8');
    } catch (e) {
      console.error('[saveSettings] 設定保存エラー:', e);
    }
  }
});
