using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;

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

public partial class SubscriptionsView : UserControl
{
    /// <summary>Initializes a new instance of the <see cref="SubscriptionsView"/> class.</summary>
    public SubscriptionsView()
    {
        InitializeComponent();
    }

    /// <inheritdoc />
    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);

        var grid = this.FindControl<DataGrid>("SubscriptionsGrid");
        if (grid != null)
        {
            grid.DoubleTapped += OnGridDoubleTapped;
            grid.SelectionChanged += OnGridSelectionChanged;
        }
    }

    private void OnGridSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (DataContext is not SubscriptionsViewModel vm || sender is not DataGrid grid) return;

        vm.SelectedSubscriptions.Clear();
        foreach (var item in grid.SelectedItems)
            if (item is SubscriptionItemViewModel sub)
                vm.SelectedSubscriptions.Add(sub);

        vm.RemoveSubscriptionCommand.NotifyCanExecuteChanged();
    }

    private void OnGridDoubleTapped(object? sender, TappedEventArgs e)
    {
        if (DataContext is not SubscriptionsViewModel vm) return;
        if (vm.SelectedSubscription is not { } item) return;

        var parentWindow = this.FindAncestorOfType<Window>();
        if (parentWindow == null) return;

        var writeWindow = new WriteValueWindow(vm, item.NodeId, item.Value);
        writeWindow.ShowDialog(parentWindow);
    }
}
