using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using RobotNet.Script.Shares;
using RobotNet.ScriptManager.Services;
using RobotNet.Shares;

namespace RobotNet.ScriptManager.Hubs;

[Authorize]
public class ScriptOpenHub(ScriptStateManager scriptBuilder, ScriptGlobalsManager globalManager) : Hub
{
    public ProcessorState GetState() => scriptBuilder.State;

    public MessageResult Run()
    {
        var message = "";
        var result = scriptBuilder.Run(ref message);

        return new(result, message);
    }

    public MessageResult Stop()
    {
        var message = "";
        var result = scriptBuilder.Stop(ref message);

        return new(result, message);
    }

    public IDictionary<string, string> GetVariables() => globalManager.GetVariablesData().ToDictionary(v => v.Name, v => v.Value);

    public string GetVariableValue(string name)
    {
        if (globalManager.Globals.TryGetValue(name, out var value))
        {
            return value?.ToString() ?? "null";
        }
        else
        {
            return "null";
        }
    }

    public bool SetVariableValue(string name, string value)
    {
        try
        {
            globalManager.SetValue(name, value);
            return true;
        }
        catch
        {
            return false;
        }
    }
    public bool ResetVariableValue(string name)
    {
        try
        {
            globalManager.ResetValue(name);
            return true;
        }
        catch
        {
            return false;
        }
    }
}
