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 HMIHub(ScriptStateManager scriptBuilder, ScriptGlobalsManager globalsManager) : Hub
{
    public ProcessorState GetState() => scriptBuilder.State;

    public ProcessorRequest GetRequest() => scriptBuilder.Request;

    public IDictionary<string, string> GetVariables(IEnumerable<string> keys)
    {
        var variables = new Dictionary<string, string>();
        foreach (var key in keys)
        {
            if (globalsManager.Globals.TryGetValue(key, out object? val))
            {
                variables.Add(key, val?.ToString() ?? "null");
            }
            else
            {
                variables.Add(key, "null");
            }
        }
        return variables;
    }

    public MessageResult SetVariable(string key, string value)
    {
        try
        {
            globalsManager.SetValue(key, value);
            return new(true, "");
        }
        catch (Exception ex)
        {
            return new(false, ex.Message);
        }
    }
}
