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

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

  bool isMovingForward = false;
  bool isMovingBackward = false;
  bool isTurningLeft = false;
  bool isTurningRight = false;

  // Discrete (triggers once per press)
  bool isInteracting = false;

  // Continuous
  bool isFiring = false;

  WeaponType? requestedWeapon;

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

    // Calculate all keys that were pressed exactly on this frame
    final newlyPressedKeys = pressedKeys.difference(_previousKeys);

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

    // * Interaction (Space)
    // Much simpler now using the newlyPressedKeys set
    isInteracting = newlyPressedKeys.contains(LogicalKeyboardKey.space);

    // * Firing (Left Control)
    // - Keeping this continuous for machine guns
    isFiring =
        pressedKeys.contains(LogicalKeyboardKey.controlLeft) &&
        !pressedKeys.contains(LogicalKeyboardKey.space);

    // * Manual Weapon Switching
    requestedWeapon = null;

    // Iterate through newly pressed keys and switch on them
    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;
      }
    }

    // * Save state for next tick
    _previousKeys = Set.from(pressedKeys);
  }
}
