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;  // 这里将存储 0-360 的角度值
    this.speed = 0;
    this.directionAxis9 = 0;
    this.rightJoystickPressed = false;
    this.isActive = false;

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

  update() {
    const gamepad = navigator.getGamepads()[0];
    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);
    }

    // 获取右摇杆的值（用于云台控制）
    const rightY = gamepad.axes[3];
    if (Math.abs(rightY) > this.options.deadZone) {
      this.directionAxis9 = rightY > 0 ? 1 : 2;
    } else {
      this.directionAxis9 = 0;
    }

    // 更新右摇杆按钮状态
    this.rightJoystickPressed = gamepad.buttons[10].pressed;

    if (this.options.debug) {
      console.log('GamepadController 状态:', {
        x: x.toFixed(2),
        y: y.toFixed(2),
        angle: this.angle,
        speed: this.speed.toFixed(2),
        directionAxis9: this.directionAxis9,
        rightJoystickPressed: this.rightJoystickPressed
      });
    }
  }

  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);

    if (this.options.debug) {
      console.log('方向计算:', {
        x: axis0,
        y: axis1,
        angle: this.angle,
        speed: this.speed
      });
    }
  }

  destroy() {
    if (this.updateLoop) {
      clearInterval(this.updateLoop);
    }
  }
}

export default GamepadController;