const { app, ipcMain, dialog, shell, session, BrowserWindow, screen } = require('electron');
const path = require('path');
const fs = require('fs');
const { 
  initDatabase, 
  handleBookOperations, 
  handleBookInfoOperations,
  getDbPath
} = require('./dbHandler');

console.log(process.versions.electron);
console.log(process.versions.chrome);

function setupIpcHandlers () {
  ipcMain.on('message-from-renderer', (event, message) => {
    console.log(message); // 输出 'Hello from renderer process'
  });

  ipcMain.handle('request-data', async (event, data) => {
    console.log(data); // 输出 'some data'
    return 'response from main process';
  });

  ipcMain.handle('get-app-version', () => {
    return app.getVersion();
  })

  ipcMain.handle('open-directory-dialog', async (event) => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory']
    });
    return result;
  });

  ipcMain.handle('open-file-path', async (event, base_path) => {
    console.log(base_path);
    if (base_path.startsWith('file://')) {
      base_path = base_path.slice(7); // 去掉 'file://'
    }
    const questionMarkIndex = base_path.indexOf('?');
    if (questionMarkIndex !== -1) {
      base_path = base_path.slice(0, questionMarkIndex); // 去掉 '?' 及其后面的内容
    }

    shell.showItemInFolder(base_path);
  });

  ipcMain.handle('open-url', (event, url) => {
    shell.openExternal(url);
  });

  ipcMain.handle('open-shell-python', async (event, data) => autoScene(event, data))

  ipcMain.on('open-url', async (event, space) => {
    const { title, url, hash } = space;
    
    // Create a unique session for each space
    const spaceSession = session.fromPartition(`persist:${hash}`);

    const primaryDisplay = screen.getPrimaryDisplay();
    const { width, height } = primaryDisplay.workAreaSize;

    // Load cookies for this session
    await loadCookiesForSession(spaceSession, space);

    // Create a new BrowserWindow with the unique session
    const win = new BrowserWindow({
      width: width,
      height: height,
      webPreferences: {
        session: spaceSession,
        contextIsolation: true,
        enableRemoteModule: true,
        webSecurity: false,
        nodeIntegration: false,
      },
    });

    win.loadURL(url);

    // Record browsing history
    recordHistory({ title, url, hash });
  });

  // 获取文件状态信息
  ipcMain.handle('get-file-stats', async (event, filePath) => {
    try {
      // 确保文件路径存在
      if (!filePath) {
        throw new Error('文件路径不能为空');
      }

      // 处理file://前缀
      if (filePath.startsWith('file://')) {
        filePath = filePath.slice(7); // 去掉 'file://'
      }

      // 解码URL编码的路径
      filePath = decodeURIComponent(filePath);

      // 检查文件是否存在
      if (!fs.existsSync(filePath)) {
        throw new Error(`文件不存在: ${filePath}`);
      }

      // 获取文件状态
      const stats = fs.statSync(filePath);
      return {
        size: stats.size,
        isFile: stats.isFile(),
        isDirectory: stats.isDirectory(),
        createdAt: stats.birthtime,
        modifiedAt: stats.mtime,
        accessedAt: stats.atime
      };
    } catch (error) {
      console.error('获取文件状态时出错:', error);
      return null;
    }
  });

  // 数据库初始化
  ipcMain.handle('db:init', async (event, forceUpdate = false) => {
    console.log('初始化数据库...');
    try {
      const result = await initDatabase(forceUpdate);
      return { success: !!result };
    } catch (error) {
      console.error('初始化数据库失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 获取数据库路径
  ipcMain.handle('db:getPath', () => {
    return getDbPath();
  });

  // Book操作
  ipcMain.handle('book:create', async (event, bookData) => {
    return await handleBookOperations.createBook(bookData);
  });

  ipcMain.handle('book:getAll', async () => {
    return await handleBookOperations.getAllBooks();
  });

  ipcMain.handle('book:getById', async (event, id) => {
    return await handleBookOperations.getBookById(id);
  });

  ipcMain.handle('book:update', async (event, { id, bookData }) => {
    return await handleBookOperations.updateBook(id, bookData);
  });

  ipcMain.handle('book:delete', async (event, id) => {
    return await handleBookOperations.deleteBook(id);
  });

  // BookInfo操作
  ipcMain.handle('bookInfo:create', async (event, bookInfoData) => {
    return await handleBookInfoOperations.createBookInfo(bookInfoData);
  });

  ipcMain.handle('bookInfo:getByBookId', async (event, bookId) => {
    return await handleBookInfoOperations.getBookInfoByBookId(bookId);
  });

  ipcMain.handle('bookInfo:update', async (event, { bookId, bookInfoData }) => {
    return await handleBookInfoOperations.updateBookInfo(bookId, bookInfoData);
  });

  ipcMain.handle('bookInfo:delete', async (event, bookId) => {
    return await handleBookInfoOperations.deleteBookInfo(bookId);
  });

  // 设置音频处理IPC处理程序
  setupAudioProcessingHandlers();

  // 保存音频文件
  ipcMain.handle('save-audio-file', async (event, { buffer, fileName, directory, projectId }) => {
    try {
      // 确保目录存在
      const dirPath = directory;
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
        console.log(`创建目录: ${dirPath}`);
      }
      
      // 保存文件
      const filePath = path.join(dirPath, fileName);
      const bufferData = Buffer.from(buffer);
      
      await fs.promises.writeFile(filePath, bufferData);
      
      return {
        success: true,
        filePath: filePath
      };
    } catch (error) {
      console.error('保存音频文件失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  });

  // 获取资源目录路径
  ipcMain.handle('get-resources-path', async () => {
    try {
      // 获取数据库所在目录作为基础目录
      const dbPath = getDbPath();
      let basePath = '';
      
      if (dbPath) {
        const lastSlashIndex = Math.max(dbPath.lastIndexOf('/'), dbPath.lastIndexOf('\\'));
        if (lastSlashIndex !== -1) {
          basePath = dbPath.substring(0, lastSlashIndex);
        }
      }
      
      // 添加资源子目录
      const resourcesPath = path.join(basePath, 'resources');
      
      // 确保目录存在
      if (!fs.existsSync(resourcesPath)) {
        fs.mkdirSync(resourcesPath, { recursive: true });
      }
      
      return {
        success: true,
        path: resourcesPath
      };
    } catch (error) {
      console.error('获取资源目录路径失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  });
}

// 辅助函数：加载cookies到会话
async function loadCookiesForSession(mySession, space) {
  if (space.cookies) {
    for (let cookie of space.cookies) {
      try {
        if (!cookie.url) {
          cookie.url = space.url;
        }
        await mySession.cookies.set(cookie);
      } catch (error) {
        console.log(error);
      }
    }
  } else {
    console.log('No cookies to load');
  }
}

// 辅助函数：记录历史
function recordHistory(spaceData) {
  // 实现历史记录逻辑
  console.log('Recording history:', spaceData);
}

// 辅助函数：自动场景（如果需要）
function autoScene(event, data) {
  // 实现autoScene逻辑
  console.log('Auto scene:', data);
  return { success: true };
}

// 音频处理相关的IPC处理程序设置
function setupAudioProcessingHandlers() {
  // 获取音频时长
  ipcMain.handle('get-audio-duration', async (event, { audioPath }) => {
    try {
      const duration = await getAudioDuration(audioPath);
      return { success: true, duration };
    } catch (error) {
      console.error('获取音频时长失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 处理项目音频
  ipcMain.handle('process-project-audio', async (event, { projectId, audioPath, segments, outputDir }) => {
    try {
      // 确保输出目录存在
      const audioDir = path.join(outputDir, 'audio');
      const projectDir = path.join(audioDir, `project_${projectId}`);
      ensureDirectoryExists(projectDir);
      
      // 获取音频总时长
      const audioDuration = await getAudioDuration(audioPath);
      console.log(`音频总时长: ${audioDuration}秒`);
      
      // 按照字幕时间切割音频
      const results = [];
      
      for (const segment of segments) {
        // 解析开始和结束时间
        const startSeconds = timeToSeconds(segment.start_time);
        const endSeconds = timeToSeconds(segment.end_time);
        const segmentDuration = endSeconds - startSeconds;
        
        // 输出文件路径
        const outputFileName = `segment_${segment.id}_${segment.segment_id}.mp3`;
        const outputFilePath = path.join(projectDir, outputFileName);
        
        console.log(`处理片段 ${segment.id}: ${startSeconds}s - ${endSeconds}s (${segmentDuration}s)`);
        
        try {
          // 切割音频
          await cutAudioSegment(audioPath, outputFilePath, startSeconds, segmentDuration);
          
          // 添加到结果
          results.push({
            segmentId: segment.id,
            originalStartTime: segment.start_time,
            originalEndTime: segment.end_time,
            outputPath: outputFilePath,
            relativePath: path.join('audio', `project_${projectId}`, outputFileName)
          });
          
        } catch (error) {
          console.error(`切割片段 ${segment.id} 失败:`, error);
        }
      }
      
      return {
        success: true,
        totalSegments: segments.length,
        processedSegments: results.length,
        segments: results
      };
    } catch (error) {
      console.error('处理项目音频失败:', error);
      return { success: false, error: error.message };
    }
  });
}

// 确保目录存在
function ensureDirectoryExists(directory) {
  if (!fs.existsSync(directory)) {
    fs.mkdirSync(directory, { recursive: true });
    console.log(`创建目录: ${directory}`);
  }
}

// 获取音频时长（秒）
function getAudioDuration(audioPath) {
  return new Promise((resolve, reject) => {
    const ffmpeg = require('fluent-ffmpeg');
    ffmpeg.ffprobe(audioPath, (err, metadata) => {
      if (err) {
        return reject(err);
      }
      resolve(metadata.format.duration);
    });
  });
}

// 转换时间格式为秒
function timeToSeconds(timeString) {
  // 处理SRT格式: 00:00:12,345
  const normalizedTime = timeString.replace(',', '.');
  const [hours, minutes, seconds] = normalizedTime.split(':').map(parseFloat);
  return hours * 3600 + minutes * 60 + seconds;
}

// 切割音频片段
function cutAudioSegment(inputFile, outputFile, startTime, duration) {
  return new Promise((resolve, reject) => {
    const ffmpeg = require('fluent-ffmpeg');
    ffmpeg(inputFile)
      .setStartTime(startTime)
      .setDuration(duration)
      .output(outputFile)
      .on('end', () => {
        console.log(`音频片段已保存: ${outputFile}`);
        resolve();
      })
      .on('error', (err) => {
        console.error('音频处理错误:', err);
        reject(err);
      })
      .run();
  });
}

module.exports = {
  setupIpcHandlers,
  setupAudioProcessingHandlers
};