using System.Drawing;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Entities.Constants;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Utils;
using PubgMod.Configs;
using PubgMod.Main.Game;
using PubgMod.Players;

namespace PubgMod;

public class GameRestarter
{
    private readonly PubgPlugin _plugin;
    private readonly PlayersManager _playersManager;
    private readonly ChatService _chatService;
    private readonly GameState _state;
    private readonly GameConfig _gameConfig;
    private readonly GameTextManager _gameTextManager;

    public GameRestarter(PubgPlugin plugin, PlayersManager playersManager, ChatService chatService, GameState state,
        GameConfig gameConfig, GameTextManager gameTextManager)
    {
        _plugin = plugin;
        _playersManager = playersManager;
        _chatService = chatService;
        _state = state;
        _gameConfig = gameConfig;
        _gameTextManager = gameTextManager;
        plugin.RegisterEventHandler<EventRoundPrestart>(OnRoundPreStart);
        plugin.RegisterEventHandler<EventPlayerDeath>(OnPlayerDeath);
        plugin.RegisterEventHandler<EventRoundEnd>(OnRoundEnd);

        plugin.AddTimer(5f, CheckPlayers, TimerFlags.REPEAT);
    }

    private HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info)
    {
        if (_state.State != State.Playing)
            return HookResult.Continue;

        var attacker = @event.Attacker;
        var victim = @event.Userid;
        /*if (attacker == null || !attacker.IsValid)
            return HookResult.Continue;*/
        if (victim != null)
            Server.NextFrame(() =>
            {
                victim.ChangeTeam(CsTeam.CounterTerrorist);
                victim.Respawn();
            });

        var aliveCount = 0;
        PubgPlayer? winner = null;
        foreach (var player in _playersManager.LoadedPlayers)
        {
            if (player!.Controller != victim && player.Controller is { PawnIsAlive: true, Team: CsTeam.Terrorist })
            {
                aliveCount++;

                winner = player;
            }
        }

        _gameTextManager.Text2.Text = $"Players alive: {aliveCount}";

        if (aliveCount == 0)
            return HookResult.Continue;

        if (aliveCount == 1)
        {
            _chatService.PrintToChatAll($"{winner!.Controller.PlayerName} won!");
            GameRulesHelper.GameRules.TerminateRound(
                10f, RoundEndReason.TerroristsWin);
        }
        else
        {
            _chatService.PrintToChatAll($"{victim!.PlayerName} eliminated. {aliveCount} players left");
        }

        return HookResult.Continue;
    }

    private HookResult OnRoundPreStart(EventRoundPrestart @event, GameEventInfo info)
    {
        if (!IsEnoughPlayers(out _))
            _state.State = State.WaitingForPlayers;
        else
        {
            foreach (var player in _playersManager.LoadedPlayers)
            {
                player!.Controller.ChangeTeam(CsTeam.Terrorist);
            }
            _state.State = State.Playing;
        }

        return HookResult.Continue;
    }

    private void CheckPlayers()
    {
        if (_state.State == State.WaitingForPlayers)
        {
            if (IsEnoughPlayers(out var playersCount))
            {
                Server.ExecuteCommand("mp_restartgame 1");
                _chatService.PrintToChatAll("Players are gathered, starting the game");
                _state.State = State.Playing;
            }
            else
            {
                var message = $"Waiting for players... {playersCount}/{_gameConfig.MinPlayers}";
                _chatService.PrintToChatAll(message);
                _gameTextManager.Text2.Text = message;
            }
        }
        else if (_state.State == State.Playing)
        {
            if (!Utilities.GetPlayers().Any(p => p is { PawnIsAlive: true, Team: CsTeam.Terrorist }))
            {
                _state.State = State.GameEnded;
                GameRulesHelper.GameRules.TerminateRound(
                    3f, RoundEndReason.RoundDraw);
            }
        }
    }

    private bool IsEnoughPlayers(out int players)
    {
        players = Utilities.GetPlayers().Count;
        return players >= _gameConfig.MinPlayers;
    }

    private HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info)
    {
        if (!IsEnoughPlayers(out _))
            _state.State = State.WaitingForPlayers;
        else
            _state.State = State.GameEnded;

        return HookResult.Continue;
    }
}




почему некоторые игроки оказываюти за КТ во время старта игры