using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;

namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;

/// <summary>
///     ViewModel for the OPC UA browse tree panel.
/// </summary>
public class BrowseTreeViewModel : ObservableObject
{
    private readonly IUiDispatcher _dispatcher;
    private readonly IOpcUaClientService _service;

    /// <summary>
    /// Initializes a new instance of the <see cref="BrowseTreeViewModel"/> class.
    /// </summary>
    /// <param name="service">The OPC UA client service.</param>
    /// <param name="dispatcher">The UI dispatcher for marshaling updates.</param>
    public BrowseTreeViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
    {
        _service = service;
        _dispatcher = dispatcher;
    }

    /// <summary>Top-level nodes in the browse tree.</summary>
    public ObservableCollection<TreeNodeViewModel> RootNodes { get; } = [];

    /// <summary>
    ///     Loads root nodes by browsing with a null parent.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    public async Task LoadRootsAsync()
    {
        var results = await _service.BrowseAsync();

        _dispatcher.Post(() =>
        {
            RootNodes.Clear();
            foreach (var result in results)
                RootNodes.Add(new TreeNodeViewModel(
                    result.NodeId,
                    result.DisplayName,
                    result.NodeClass,
                    result.HasChildren,
                    _service,
                    _dispatcher));
        });
    }

    /// <summary>
    ///     Clears all root nodes from the tree.
    /// </summary>
    public void Clear()
    {
        RootNodes.Clear();
    }
}