import 'package:flutter/services.dart';
import 'package:wolf_3d_engine/wolf_3d_engine.dart';
import 'package:wolf_3d_entities/wolf_3d_entities.dart';

class WolfInput {
  Set<LogicalKeyboardKey> _previousKeys = {};

  bool isMovingForward = false;
  bool isMovingBackward = false;
  bool isTurningLeft = false;
  bool isTurningRight = false;
  bool isInteracting = false;
  bool isFiring = false;
  WeaponType? requestedWeapon;

  void update() {
    final pressedKeys = HardwareKeyboard.instance.logicalKeysPressed;
    final newlyPressedKeys = pressedKeys.difference(_previousKeys);

    isMovingForward = pressedKeys.contains(LogicalKeyboardKey.keyW);
    isMovingBackward = pressedKeys.contains(LogicalKeyboardKey.keyS);
    isTurningLeft = pressedKeys.contains(LogicalKeyboardKey.keyA);
    isTurningRight = pressedKeys.contains(LogicalKeyboardKey.keyD);

    isInteracting = newlyPressedKeys.contains(LogicalKeyboardKey.space);

    isFiring =
        pressedKeys.contains(LogicalKeyboardKey.controlLeft) &&
        !pressedKeys.contains(LogicalKeyboardKey.space);

    requestedWeapon = null;
    for (final LogicalKeyboardKey key in newlyPressedKeys) {
      switch (key) {
        case LogicalKeyboardKey.digit1:
          requestedWeapon = WeaponType.knife;
        case LogicalKeyboardKey.digit2:
          requestedWeapon = WeaponType.pistol;
        case LogicalKeyboardKey.digit3:
          requestedWeapon = WeaponType.machineGun;
        case LogicalKeyboardKey.digit4:
          requestedWeapon = WeaponType.chainGun;
      }
    }

    _previousKeys = Set.from(pressedKeys);
  }

  /// Exports the current state as a clean DTO for the engine
  EngineInput get currentInput => EngineInput(
    isMovingForward: isMovingForward,
    isMovingBackward: isMovingBackward,
    isTurningLeft: isTurningLeft,
    isTurningRight: isTurningRight,
    isFiring: isFiring,
    isInteracting: isInteracting,
    requestedWeapon: requestedWeapon,
  );
}
