using API.Models.DataClasses;
using API.Models.Game;
using API.Services.GameManager;
using Microsoft.AspNetCore.SignalR;

namespace API.Controllers;

public class GameHubSocket(IGameManager gameManager) : Hub
{
    private readonly IGameManager _gameManager = gameManager;

    public async Task CreateGame(string playerName, Coordinates gFs)
    {
        if (gFs.X <= 0 || gFs.Y <= 0)
        {
            await Clients.Caller.SendAsync("Error", "Ungültige Spielfeldgröße.");
            return;
        }

        var player = new Player(playerName, Context.ConnectionId);

        var result = _gameManager.CreateGame(gFs, player);

        await Groups.AddToGroupAsync(Context.ConnectionId, result.Item1);

        await Clients.Caller.SendAsync("GameCreated", new
        {
            GameId = result.Item1,
            GameCode = result.Item2,
        });
    }

    public async Task JoinGame(string playerName, int gameCode)
    {
        var player = new Player(playerName, Context.ConnectionId);

        var result = await _gameManager.JoinGame(player, gameCode);

        if (result == null)
        {
            await Clients.Caller.SendAsync("Error", "Spiel nicht gefunden oder voll.");
            return;
        }

        await Groups.AddToGroupAsync(Context.ConnectionId, result);

        await Clients.Caller.SendAsync("GameJoined", new
        {
            GameId = result,
            GameCode = gameCode,
        });
    }

    public async Task RequestGameInformation(string gameId)
    {
        await _gameManager.RequestGameInformation(gameId, Context.ConnectionId);
    }

    public async Task Drop(string gameId, int column)
    {
        await _gameManager.Drop(gameId, column, Context.ConnectionId);
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        await _gameManager.DisconnectedPlayer(Context.ConnectionId);

        await base.OnDisconnectedAsync(exception);
    }
}
