import 'package:werwolf/models/role.dart';
import 'player.dart';

class Game {
  // List to store player objects
  List<Player> players = [];
  
  // List to store player names
  List playernames = [];
  
  // Initial number of werewolves
  int numWolves = 1;
  
  // Map to store special roles and their activation status
  Map specialRoles = <Role, bool>{};

  // Constructor to initialize the game with player names
  Game({required this.playernames}) {
    // Initialize specialRoles map, setting all special roles to false
    for (Role role in Role.values) {
      if (role != Role.dorfbewohner && role != Role.werwolf) {
        specialRoles[role] = false;
      }
    }
  }

  // Method to increment the number of werewolves
  void incrementWolves() {
    // Increment only if conditions are met: enough players and balance maintained
    if (numWolves < playernames.length - 1 &&
        (playernames.length) >= ((numWolves + 1) * 3)) {
      numWolves++;
    }
  }

  // Method to decrement the number of werewolves
  void decrementWolves() {
    // Decrement only if there's more than one werewolf
    if (numWolves > 1) {
      numWolves--;
    }
  }

  // Method to get the current number of werewolves
  int getWolves() {
    return numWolves;
  }

  // Method to get all players with their assigned roles
  List<Player> getAllPlayers() {
    // Clear the players list to start fresh
    players.clear();
    
    // List to hold roles randomly assigned to players
    List<Role> randomRoles = [];
    
    // Add werewolf roles to the list
    for (var i = 0; i < numWolves; i++) {
      randomRoles.add(Role.werwolf);
    }
    
    // Add active special roles to the list
    for (var specialRole in specialRoles.keys) {
      if (specialRoles[specialRole]) {
        randomRoles.add(specialRole);
      }
    }
    
    // Fill the remaining roles with dorfbewohner
    for (var i = randomRoles.length; i < playernames.length; i++) {
      randomRoles.add(Role.dorfbewohner);
    }
    
    // Shuffle the roles to ensure randomness
    randomRoles.shuffle();
    
    // Assign roles to players and create Player objects
    for (var playerName in playernames) {
      players
          .add(Player(name: playerName, role: randomRoles.last, isDead: false));
      randomRoles.removeLast();
    }
    
    // Return the list of players with their roles
    return players;
  }
}
