class GamepadController {
  constructor(options = {}) {
    this.options = {
      ...{
        debug: false,
        deadZone: 0.1,
        updateInterval: 50
      },
      ...options
    };

    this.gamepadIndex = null;
    this.gamepad = null;
    this.interval = null;
    this.angle = 0;
    this.speed = 0;
    this.directionAxis9 = 0;
    this.rightJoystickPressed = false;
    this.isActive = false;

    // 立即开始更新循环，不等待连接事件
    this.startUpdateLoop();
  }

  update() {
    // 获取所有手柄
    const gamepads = navigator.getGamepads();
    if (!gamepads) {
      this.isActive = false;
      return;
    }

    // 找到第一个连接的手柄
    const gamepad = Array.from(gamepads).find(pad => pad && pad.connected);
    if (!gamepad) {
      this.isActive = false;
      return;
    }

    this.isActive = true;
    
    // 获取左摇杆的值
    const x = gamepad.axes[0];
    const y = gamepad.axes[1];

    // 应用死区
    const absX = Math.abs(x);
    const absY = Math.abs(y);
    
    if (absX < this.options.deadZone && absY < this.options.deadZone) {
      this.angle = 0;
      this.speed = 0;
    } else {
      this.updateDirection(gamepad.axes);
    }

    // 更新 platform 值
    this.updateDirectionAxis9(gamepad.axes);

    // 更新右摇杆按钮状态 - 尝试多个可能的按钮索引
    this.rightJoystickPressed = 
      (gamepad.buttons[10] && gamepad.buttons[10].pressed) || 
      (gamepad.buttons[9] && gamepad.buttons[9].pressed) || 
      (gamepad.buttons[11] && gamepad.buttons[11].pressed);

    if (this.options.debug) {
      console.log('GamepadController 状态:', {
        id: gamepad.id,
        index: gamepad.index,
        x: x.toFixed(2),
        y: y.toFixed(2),
        angle: this.angle,
        speed: this.speed.toFixed(2),
        directionAxis9: this.directionAxis9,
        rightJoystickPressed: this.rightJoystickPressed,
        buttons: Array.from(gamepad.buttons).map((btn, idx) => btn.pressed ? idx : null).filter(idx => idx !== null)
      });
    }
  }

  updateDirection(axes) {
    const axis0 = axes[0];  // X轴
    const axis1 = axes[1];  // Y轴

    // 检查是否在死区
    if (Math.abs(axis0) < this.options.deadZone && Math.abs(axis1) < this.options.deadZone) {
      this.angle = 0;
      this.speed = 0;
      return;
    }

    // 计算角度（0-360度），从x轴正半轴开始顺时针旋转
    let angle = Math.atan2(axis1, axis0) * (180 / Math.PI);
    // 将角度转换到 0-360 范围
    if (angle < 0) {
      angle += 360;
    }
    this.angle = Math.round(angle);

    // 计算速度（0-100）
    const distance = Math.sqrt(axis0 * axis0 + axis1 * axis1);
    this.speed = Math.min(Math.round(distance * 100), 100);
  }

  updateDirectionAxis9(axes) {
    // 添加调试输出，查看所有轴的值
    if (this.options.debug) {
      // console.log('所有轴的值:', axes.map((value, index) => `轴${index}: ${value}`));
    }

    // 检查第9轴是否存在
    if (axes[9] === undefined) {
      // 可能是第3轴或第4轴
      const axis3 = axes[3];
      const axis4 = axes[4];
      
      if (axis3 !== undefined && Math.abs(axis3) > this.options.deadZone) {
        this.directionAxis9 = axis3 > 0 ? 2 : 1;
      } else if (axis4 !== undefined && Math.abs(axis4) > this.options.deadZone) {
        this.directionAxis9 = axis4 > 0 ? 2 : 1;
      } else {
        this.directionAxis9 = 0;
      }
    } else {
      const axis9 = axes[9];
      const roundedAxis9 = Math.round(axis9 * 100) / 100;
      if (roundedAxis9 <= -0.9) {
        this.directionAxis9 = 1;  // 向上
      } else if (roundedAxis9 >= 0.0 && roundedAxis9 <= 0.2) {
        this.directionAxis9 = 2;  // 向下
      } else {
        this.directionAxis9 = 0;  // 中间位置
      }
    }

    if (this.options.debug) {
      // console.log('当前 directionAxis9 值:', this.directionAxis9);
    }
  }

  startUpdateLoop() {
    this.updateLoop = setInterval(() => this.update(), this.options.updateInterval);
  }

  destroy() {
    if (this.updateLoop) {
      clearInterval(this.updateLoop);
    }
  }
}export default GamepadController;

