using Avalonia.Controls;
using OTSSignsOrchestrator.Desktop.ViewModels;

namespace OTSSignsOrchestrator.Desktop.Views;

public partial class InstancesView : UserControl
{
    private InstancesViewModel? _vm;

    public InstancesView()
    {
        InitializeComponent();
        DataContextChanged += OnDataContextChanged;
    }

    private void OnDataContextChanged(object? sender, EventArgs e)
    {
        if (_vm is not null)
            _vm.OpenDetailsRequested -= OnOpenDetailsRequested;

        _vm = DataContext as InstancesViewModel;

        if (_vm is not null)
            _vm.OpenDetailsRequested += OnOpenDetailsRequested;
    }

    private async void OnOpenDetailsRequested(InstanceDetailsViewModel detailsVm)
    {
        var window = new InstanceDetailsWindow { DataContext = detailsVm };
        var owner  = TopLevel.GetTopLevel(this) as Window;
        if (owner is not null)
            await window.ShowDialog(owner);
        else
            window.Show();
    }
}

