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

const execAsync = promisify(exec);

// 获取设备分辨率
export async function getDeviceResolution(ipPort) {
  if (!ipPort) {
    return { success: false, error: '缺少设备 ID' };
  }
  try {
    // 使用 wm size 命令获取设备分辨率
    const adbPath = getCachedAdbPath();
    const { stdout } = await execAsync(`${adbPath} -s ${ipPort} shell wm size`);
    // 输出格式通常是: "Physical size: 1080x2400" 或 "1080x2400"
    const match = stdout.match(/(\d+)x(\d+)/);
    if (match) {
      return {
        success: true,
        width: parseInt(match[1], 10),
        height: parseInt(match[2], 10)
      };
    }
    // 如果解析失败，返回默认值
    return { success: true, width: 1280, height: 2400 };
  } catch (error) {
    console.error('获取设备分辨率失败:', error);
    // 返回默认值
    return { success: true, width: 1280, height: 2400 };
  }
}

// 注册 IPC 处理器
export function registerIpcHandlers() {
  // IPC 处理程序：获取设备分辨率
  ipcMain.handle('get-device-resolution', async (event, ipPort) => {
    return await getDeviceResolution(ipPort);
  });
}

