using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using RobotNet.RobotManager.Services;
using RobotNet.RobotManager.Services.Traffic;
using RobotNet.RobotShares.Dtos;
using RobotNet.Shares;

namespace RobotNet.RobotManager.Hubs;

[Authorize]
public class TrafficHub(TrafficPublisher TrafficPublisher, TrafficManager TrafficManager, MapManager MapManager, LoggerController<RobotHub> Logger) : Hub
{
    public async Task TrafficActive(Guid mapId)
    {
        var keysToRemove = TrafficPublisher.TrafficMapActive.Where(kvp => kvp.Value == Context.ConnectionId)
                            .Select(kvp => kvp.Key)
                            .ToList();
        foreach (var key in keysToRemove)
        {
            TrafficPublisher.TrafficMapActive.Remove(key);
        }

        TrafficPublisher.TrafficMapActive[mapId] = Context.ConnectionId;
        await Clients.AllExcept([.. TrafficPublisher.TrafficMapActive.Values]).SendAsync("TrafficManagerDeactive");
    }

    public async Task<MessageResult<IEnumerable<TrafficMapDto>>> LoadTrafficMaps()
    {
        try
        {
            List<TrafficMapDto> trafficMaps = [];
            foreach (var trafficMap in TrafficManager.TrafficMaps)
            {
                var map = await MapManager.GetMapData(trafficMap.Key);
                trafficMaps.Add(new()
                {
                    MapId = trafficMap.Key,
                    Agents = TrafficPublisher.GetAgents(trafficMap.Key),
                    MapName = map.Data is null ? "" : map.Data.Name,
                });
            }
            return new(true) { Data = trafficMaps };
        }
        catch (Exception ex)
        {
            Logger.Warning($"LoadTrafficMaps: Hệ thống có lỗi xảy ra - {ex.Message}");
            return new(false, "Hệ thống có lỗi xảy ra");
        }
    }

    public async Task<MessageResult<TrafficMapDto>> LoadTrafficMap(Guid mapId)
    {
        try
        {
            var map = await MapManager.GetMapData(mapId);
            var trafficMap = new TrafficMapDto()
            {
                MapId = mapId,
                Agents = TrafficPublisher.GetAgents(mapId),
                MapName = map.Data is null ? "" : map.Data.Name,
            };
            return new(true) { Data = trafficMap };
        }
        catch (Exception ex)
        {
            Logger.Warning($"LoadTrafficMaps: Hệ thống có lỗi xảy ra - {ex.Message}");
            return new(false, "Hệ thống có lỗi xảy ra");
        }
    }
}
