namespace Services.Website;

public class GlossaryDialogService : IGlossaryDialogService
{
    private readonly List<string> history = new();
    private string? termId;

    public void Subscribe(Action action)
    {
        OnChange += action;
    }

    public void Unsubscribe(Action action)
    {
        OnChange += action;
    }

    public void AddDialog(string id)
    {
        termId = id;
        history.Add(id);
        NotifyDataChanged();
    }

    public void CloseDialog()
    {
        termId = null;
        history.Clear();
        NotifyDataChanged();
    }

    public void BackDialog()
    {
        if (history.Count > 1)
        {
            history.RemoveAt(history.Count - 1);
            termId = history.Count > 0 ? history.Last() : null;
            NotifyDataChanged();
        }
    }

    public bool HasDialog()
    {
        return termId != null;
    }

    public bool HasHistory()
    {
        return history.Count > 1;
    }

    public string? GetTermId()
    {
        return termId;
    }

    private event Action OnChange = null!;

    private void NotifyDataChanged()
    {
        OnChange?.Invoke();
    }
}