// 创建一个变量来存储ffmpeg模块
let ffmpegModuleInstance: any = null;

// 添加类型定义
interface FFmpegProgress {
  percent: number;
}

interface FFmpegError extends Error {
  code?: string;
}

type ProcessType = "mac" | "win";

interface IpcMainInvokeEvent {
  sender: any;
  frameId: number;
}

const init = (remoteMain: any) => {
  //@ts-ignore
  const { app, BrowserWindow, ipcMain, webContents } = require("electron");
  const Store = require("electron-store");
  const path = require("path");
  const fs = require("fs");

  // 添加缺失的变量声明
  const args = process.argv;
  const manifest = require("../package.json");
  const { exec } = require("child_process");

  const store = new Store();

  // 在try-catch块中加载模块
  try {
    const ffmpegTemp = require("fluent-ffmpeg");
    const ffmpegPath = require("ffmpeg-static");

    ffmpegTemp.setFfmpegPath(ffmpegPath);
    // 使用我们创建的变量而不是global
    ffmpegModuleInstance = ffmpegTemp;
    console.log("FFmpeg loaded successfully, path:", ffmpegPath);
  } catch (error) {
    console.error("FFmpeg module loading error:", error);
    console.error(
      "Module not found",
      "Please run `npm install fluent-ffmpeg` and `npm install ffmpeg-static` and update electron version to 22.0.0 or higher"
    );
  }

  ipcMain.on("enable-remote", (event: any, webContentsId: any) => {
    const target = webContents.fromId(webContentsId);
    remoteMain.enable(target); // 主进程操作‌:ml-citation{ref="4" data="citationList"}
  });

  // 目前使用了第三个 --- relaunch
  ipcMain.on("synchronous-message", (event: any, arg: any) => {
    let cmd = arg,
      params = [];
    if (typeof arg == "object" && !Array.isArray(arg)) {
      cmd = arg.cmd;
      params = arg.params;
    }
    switch (cmd) {
      case "argv":
        event.returnValue = args;
        break;
      case "manifest":
        event.returnValue = manifest;
        break;
      case "relaunch":
        ipcMain.removeAllListeners();
        console.log("relaunch");
        break;
      case "quit":
        app.exit();
        break;
      case "shareToQQ":
        {
          const shareWin = new BrowserWindow();
          try {
            require("@electron/remote/main").enable(shareWin.webContents);
          } catch (error) {
            console.error(
              "Module not found",
              "Please run `npm install @electron/remote` to enable remote module and update electron version to 22.0.0 or higher"
            );
          }

          shareWin.loadURL(params);
        }
        break;
      default:
        event.returnValue = "no such command!!";
        break;
    }
  });

  ipcMain.handle("getStoreValue", (event: any, key: any) => {
    return store.get(key);
  });

  ipcMain.handle("setStoreValue", (event: any, key: any, value: any) => {
    store.set(key, value);
    return true;
  });

  // 转换wav to mp3
  ipcMain.handle(
    "convert-audio",
    (event: any, { inputPath, outputPath }: any) => {
      console.log("Convert-audio called with:", { inputPath, outputPath });

      // 检查参数
      if (!inputPath || !outputPath) {
        console.error("Missing required parameters");
        return Promise.reject(
          new Error("Missing required parameters: inputPath or outputPath")
        );
      }

      // 检查ffmpeg是否正确加载
      if (!ffmpegModuleInstance) {
        console.error("FFmpeg module not loaded");
        return Promise.reject(
          new Error(
            "FFmpeg module not loaded. Please install fluent-ffmpeg and ffmpeg-static packages."
          )
        );
      }

      // 检查输入文件是否存在
      try {
        if (!fs.existsSync(inputPath)) {
          console.error("Input file does not exist:", inputPath);
          return Promise.reject(
            new Error(`Input file does not exist: ${inputPath}`)
          );
        }
      } catch (error) {
        console.error("Error checking input file:", error);
        return Promise.reject(error);
      }

      // 确保输出目录存在
      try {
        const outputDir = path.dirname(outputPath);
        if (!fs.existsSync(outputDir)) {
          fs.mkdirSync(outputDir, { recursive: true });
          console.log("Created output directory:", outputDir);
        }
      } catch (error) {
        console.error("Error creating output directory:", error);
        return Promise.reject(error);
      }

      console.log("Starting audio conversion...");

      return new Promise((resolve, reject) => {
        ffmpegModuleInstance()
          .input(inputPath)
          .audioCodec("libmp3lame")
          .audioBitrate(192)
          .toFormat("mp3")
          .on("start", (commandLine: string) => {
            console.log("FFmpeg process started:", commandLine);
          })
          .on("progress", (progress: FFmpegProgress) => {
            console.log(`Processing: ${Math.floor(progress.percent)}% done`);
          })
          .on("end", () => {
            console.log("Conversion completed successfully");
            resolve(outputPath);
          })
          .on("error", (err: FFmpegError) => {
            console.error("Conversion error:", err);
            reject(err);
          })
          .save(outputPath);
      });
    }
  );
  // 获取进程
  const getData = (type: ProcessType) => {
    const cmd = type === "mac" ? "ps -Aco command" : "tasklist";
    return new Promise((resolve, reject) => {
      exec(cmd, (err: Error | null, stdout: string) => {
        if (err) {
          return console.error(err);
        }
        if (stdout) {
          resolve(stdout);
        }
      });
    });
  };

  ipcMain.handle(
    "getSystemProcess",
    async (event: IpcMainInvokeEvent, type: ProcessType) => {
      // @ts-ignore
      const data = await getData(type);
      return data;
    }
  );
};

export { init };
