using NexusReader.Application.Queries.Graph;

namespace NexusReader.UI.Shared.Services;

public sealed class KnowledgeGraphService : IKnowledgeGraphService
{
    public GraphDataDto? CurrentGraphData { get; private set; }
    public string? ActiveNodeId { get; private set; }
    public bool IsLoading { get; private set; }

    public event Func<Task>? OnGraphUpdated;
    public event Func<string, Task>? OnActiveNodeChanged;
    public event Func<bool, Task>? OnLoadingChanged;

    public async Task UpdateGraph(GraphDataDto newData)
    {
        CurrentGraphData = newData;
        IsLoading = false;
        if (OnLoadingChanged != null) await OnLoadingChanged(false);
        if (OnGraphUpdated != null) await OnGraphUpdated();
    }

    public async Task SetActiveNode(string nodeId)
    {
        if (ActiveNodeId == nodeId) return;
        ActiveNodeId = nodeId;
        if (OnActiveNodeChanged != null) await OnActiveNodeChanged(nodeId);
    }

    public async Task SetLoading(bool isLoading)
    {
        IsLoading = isLoading;
        if (OnLoadingChanged != null) await OnLoadingChanged(isLoading);
    }

    public async Task Clear()
    {
        CurrentGraphData = null;
        ActiveNodeId = null;
        IsLoading = false;
        if (OnGraphUpdated != null) await OnGraphUpdated();
    }
}
