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

const execAsync = promisify(exec);

// 发送 tap 事件到设备
export async function sendTap(ipPort, x, y) {
  if (!ipPort) {
    return { success: false, error: '缺少设备 ID' };
  }
  if (typeof x !== 'number' || typeof y !== 'number') {
    return { success: false, error: '坐标必须是数字' };
  }
  try {
    const adbPath = getCachedAdbPath();
    const command = `${adbPath} -s ${ipPort} shell input tap ${x} ${y}`;
    await execAsync(command, {
      timeout: 5000,
      maxBuffer: 1024 * 1024
    });
    return { success: true };
  } catch (error) {
    console.error('Tap 失败:', error.message);
    return { success: false, error: error.message };
  }
}

// 发送 swipe 事件到设备
export async function sendSwipe(ipPort, x1, y1, x2, y2, duration = 300) {
  if (!ipPort) {
    return { success: false, error: '缺少设备 ID' };
  }
  if (typeof x1 !== 'number' || typeof y1 !== 'number' || typeof x2 !== 'number' || typeof y2 !== 'number') {
    return { success: false, error: '坐标必须是数字' };
  }
  try {
    const adbPath = getCachedAdbPath();
    const command = `${adbPath} -s ${ipPort} shell input swipe ${x1} ${y1} ${x2} ${y2} ${duration}`;
    await execAsync(command, {
      timeout: 5000,
      maxBuffer: 1024 * 1024
    });
    return { success: true };
  } catch (error) {
    console.error('Swipe 失败:', error.message);
    return { success: false, error: error.message };
  }
}

// 转义文字中的特殊字符
function escapeText(text) {
  return text
    .replace(/\\/g, '\\\\')  // 先转义反斜杠
    .replace(/'/g, "'\\''")   // 转义单引号
    .replace(/ /g, '%s')      // 空格转换为 %s
    .replace(/&/g, '\\&')     // 转义 &
    .replace(/</g, '\\<')     // 转义 <
    .replace(/>/g, '\\>')     // 转义 >
    .replace(/\(/g, '\\(')    // 转义 (
    .replace(/\)/g, '\\)')    // 转义 )
    .replace(/;/g, '\\;')     // 转义 ;
    .replace(/\|/g, '\\|')    // 转义 |
    .replace(/\*/g, '\\*')    // 转义 *
    .replace(/\?/g, '\\?')    // 转义 ?
    .replace(/`/g, '\\`')     // 转义 `
    .replace(/\$/g, '\\$')    // 转义 $
    .replace(/"/g, '\\"');    // 转义 "
}

// 发送文字到设备
export async function sendText(ipPort, text) {
  if (!ipPort) {
    return { success: false, error: '缺少设备 ID' };
  }
  if (typeof text !== 'string') {
    return { success: false, error: '文字必须是字符串' };
  }
  try {
    const adbPath = getCachedAdbPath();
    
    // 对于换行，使用 KEYCODE_ENTER
    if (text.includes('\n')) {
      // 如果有换行，分段发送
      const lines = text.split('\n');
      for (let i = 0; i < lines.length; i++) {
        if (lines[i]) {
          const escapedLine = escapeText(lines[i]);
          await execAsync(`${adbPath} -s ${ipPort} shell input text "${escapedLine}"`, {
            timeout: 5000,
            maxBuffer: 1024 * 1024
          });
        }
        // 发送换行（除了最后一行）
        if (i < lines.length - 1) {
          await execAsync(`${adbPath} -s ${ipPort} shell input keyevent KEYCODE_ENTER`, {
            timeout: 5000,
            maxBuffer: 1024 * 1024
          });
        }
      }
    } else {
      // 没有换行，直接发送
      const escapedText = escapeText(text);
      const command = `${adbPath} -s ${ipPort} shell input text "${escapedText}"`;
      await execAsync(command, {
        timeout: 5000,
        maxBuffer: 1024 * 1024
      });
    }
    
    return { success: true };
  } catch (error) {
    console.error('发送文字失败:', error.message);
    return { success: false, error: error.message };
  }
}

// 发送按键事件到设备
export async function sendKeyEvent(ipPort, keyCode) {
  if (!ipPort) {
    return { success: false, error: '缺少设备 ID' };
  }
  if (typeof keyCode !== 'string') {
    return { success: false, error: '按键代码必须是字符串' };
  }
  try {
    const adbPath = getCachedAdbPath();
    const command = `${adbPath} -s ${ipPort} shell input keyevent ${keyCode}`;
    await execAsync(command, {
      timeout: 5000,
      maxBuffer: 1024 * 1024
    });
    return { success: true };
  } catch (error) {
    console.error('发送按键失败:', error.message);
    return { success: false, error: error.message };
  }
}

// 注册 IPC 处理器
export function registerIpcHandlers() {
  // IPC 处理程序：发送 tap 事件到设备
  ipcMain.handle('send-tap', async (event, ipPort, x, y) => {
    return await sendTap(ipPort, x, y);
  });

  // IPC 处理程序：发送 swipe 事件到设备
  ipcMain.handle('send-swipe', async (event, ipPort, x1, y1, x2, y2, duration = 300) => {
    return await sendSwipe(ipPort, x1, y1, x2, y2, duration);
  });

  // IPC 处理程序：发送文字到设备
  ipcMain.handle('send-text', async (event, ipPort, text) => {
    return await sendText(ipPort, text);
  });

  // IPC 处理程序：发送按键事件到设备
  ipcMain.handle('send-key-event', async (event, ipPort, keyCode) => {
    return await sendKeyEvent(ipPort, keyCode);
  });
}

