using Microsoft.AspNetCore.SignalR;
using RobotNet.ScriptManager.Hubs;

namespace RobotNet.ScriptManager.Models;

public class ScriptMissionLogger(IHubContext<ConsoleHub> consoleHub, Guid missionId) : Script.ILogger
{
    private string log = "";
    private readonly Mutex mutexLog = new();
    public void LogError(string message)
    {
        _ = Task.Factory.StartNew(Task () => consoleHub.Clients.Groups("alls", "missions", $"mission-{missionId}").SendAsync("MessageError", message));

        mutexLog.WaitOne();
        log += $"E {DateTime.UtcNow} {message}{Environment.NewLine}";
        mutexLog.ReleaseMutex();
    }

    public void LogError(Exception ex) => LogError($"{ex.GetType().FullName} {ex.Message}");

    public void LogInfo(string message)
    {
        _ = Task.Factory.StartNew(Task () => consoleHub.Clients.Groups("alls", "missions", $"mission-{missionId}").SendAsync("MessageInfo", message));

        mutexLog.WaitOne();
        log += $"I {DateTime.UtcNow} {message}{Environment.NewLine}";
        mutexLog.ReleaseMutex();
    }

    public void LogWarning(string message)
    {
        _ = Task.Factory.StartNew(Task () => consoleHub.Clients.Groups("alls", "missions", $"mission-{missionId}").SendAsync("MessageWarning", message));

        mutexLog.WaitOne();
        log += $"W {DateTime.UtcNow} {message}{Environment.NewLine}";
        mutexLog.ReleaseMutex();
    }

    public string GetLog()
    {
        mutexLog.WaitOne();
        var result = log;
        log = ""; // Clear log after reading
        mutexLog.ReleaseMutex();
        return result;
    }
}
