import { ipcMain, BrowserWindow } from 'electron';
import { exec } from 'child_process';
import { promisify } from 'util';
import { getCachedAdbPath, loadConfig } from '../config.js';

const execAsync = promisify(exec);

// 获取主窗口引用（用于实时推送设备发现事件）
function getMainWindow() {
  const windows = BrowserWindow.getAllWindows();
  return windows.length > 0 ? windows[0] : null;
}

// 获取已连接的 ADB 设备列表
export async function getADBDevices() {
  try {
    const adbPath = getCachedAdbPath();
    const { stdout } = await execAsync(`${adbPath} devices`);
    const lines = stdout.split('\n').slice(1);
    const devices = [];
    
    for (const line of lines) {
      const parts = line.trim().split(/\s+/);
      if (parts.length >= 2 && parts[0] && parts[1] === 'device') {
        devices.push({
          id: parts[0],
          status: parts[1]
        });
      }
    }
    return devices;
  } catch (error) {
    console.error('获取设备列表失败:', error);
    return [];
  }
}

// 网络扫描：从 192.168.0.1 开始扫描网段，尝试连接设备（实时推送结果）
export async function scanNetworkDevices(event) {
  const adbPath = getCachedAdbPath();
  const baseIP = '192.168.0';
  const port = 5555;
  const maxConcurrent = 20; // 限制并发数，避免过载
  const connectTimeout = 1500; // 连接超时时间（毫秒）
  
  // 生成 IP 地址列表
  const ipList = [];
  for (let i = 1; i <= 255; i++) {
    ipList.push(`${baseIP}.${i}`);
  }
  
  const foundDevices = new Set(); // 使用 Set 避免重复
  
  // 分批并发扫描
  for (let i = 0; i < ipList.length; i += maxConcurrent) {
    const batch = ipList.slice(i, i + maxConcurrent);
    const promises = batch.map(async (ip) => {
      const ipPort = `${ip}:${port}`;
      try {
        // 先尝试连接设备
        await execAsync(`${adbPath} connect ${ipPort}`, {
          timeout: connectTimeout,
          maxBuffer: 1024 * 1024
        });
        
        // 连接后稍等片刻，让设备注册到 ADB 服务器
        await new Promise(resolve => setTimeout(resolve, 500));
      } catch (error) {
        // 连接失败是正常的，继续检查设备列表
      }
      
      // 直接使用 adb -s IP:PORT devices 命令检查该设备是否在列表中
      try {
        const { stdout } = await execAsync(`${adbPath} -s ${ipPort} devices`, {
          timeout: 2000,
          maxBuffer: 1024 * 1024
        });
        
        // 检查输出中是否包含 IP:PORT，如果有则说明设备存在
        if (stdout.includes(ipPort)) {
          // 发现设备，实时推送
          if (!foundDevices.has(ipPort)) {
            foundDevices.add(ipPort);
            const device = {
              id: ipPort,
              status: 'device'
            };
            // 实时发送发现的设备
            if (event && event.sender) {
              event.sender.send('device-found', device);
            } else {
              const mainWindow = getMainWindow();
              if (mainWindow) {
                mainWindow.webContents.send('device-found', device);
              }
            }
            console.log('发现设备:', ipPort);
          }
          return ipPort;
        }
      } catch (checkError) {
        // 检查失败，忽略
      }
      return null;
    });
    
    await Promise.all(promises);
  }
  
  // 返回所有发现的设备
  return Array.from(foundDevices).map(ipPort => ({
    id: ipPort,
    status: 'device'
  }));
}

// 连接 ADB 设备
export async function connectDevice(ipPort) {
  try {
    const adbPath = getCachedAdbPath();
    await execAsync(`${adbPath} connect ${ipPort}`);
    return { success: true };
  } catch (error) {
    console.error('连接设备失败:', error);
    return { success: false, error: error.message };
  }
}

// 注册 IPC 处理器
export function registerIpcHandlers() {
  // IPC 处理程序：获取 ADB 路径配置
  ipcMain.handle('get-adb-path-config', async () => {
    const config = loadConfig();
    return config ? config['adb-path'] : null;
  });

  // IPC 处理程序：获取 ADB 设备列表
  ipcMain.handle('get-adb-devices', async () => {
    return await getADBDevices();
  });

  // IPC 处理程序：扫描网络设备（支持实时推送）
  ipcMain.handle('scan-adb-devices', async (event) => {
    try {
      const devices = await scanNetworkDevices(event);
      return devices;
    } catch (error) {
      console.error('网络扫描失败:', error);
      return [];
    }
  });

  // IPC 处理程序：连接 ADB 设备
  ipcMain.handle('connect-adb-device', async (event, ipPort) => {
    return await connectDevice(ipPort);
  });
}

