import { dialog, ipcMain } from 'electron';
import fs from 'fs';
import AudioChannels from './channels';
import { LoadAudioBufferArgs, LoadAudioBufferResult } from './types';
import PythonSubprocessManager from '../main/service';

export default function registerAudioIpcHandlers() {
  ipcMain.handle(
    AudioChannels.LOAD_AUDIO_BUFFER,
    async (_, args: LoadAudioBufferArgs): Promise<LoadAudioBufferResult> => {
      try {
        const buffer = await fs.promises.readFile(args.filePath);
        return { buffer };
      } catch (err: any) {
        return { error: err.message };
      }
    },
  );

  ipcMain.handle(AudioChannels.GET_PORT, async () => {
    try {
      if (PythonSubprocessManager.instance?.portNumber) {
        return { port: PythonSubprocessManager.instance.portNumber };
      }

      return { error: 'Port number not available yet.' };
    } catch (err: any) {
      return { error: err.message };
    }
  });

  ipcMain.handle(AudioChannels.RESTART_SERVICE, async () => {
    try {
      PythonSubprocessManager.instance?.restart();
      return { success: true };
    } catch (err: any) {
      return { success: false, error: err.message };
    }
  });
}
