using System.Collections.Specialized;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Predictalytics.Shell.ViewModels;

namespace Predictalytics.Shell.Views;

public partial class MainWindow : Window
{
    private MainWindowViewModel? _vm;

    public MainWindow()
    {
        InitializeComponent();
    }

    public MainWindow(MainWindowViewModel viewModel) : this()
    {
        _vm = viewModel;
        DataContext = viewModel;

        // Dialoge kann nur das Fenster zeigen — das ViewModel bekommt sie als Rueckrufe.
        viewModel.ShowInfo = (title, message) => Dialogs.ShowInfoAsync(this, title, message);
        viewModel.ShowError = (title, message) => Dialogs.ShowErrorAsync(this, title, message);
        viewModel.ShowConfirm = (title, message) => Dialogs.ShowConfirmAsync(this, title, message);

        // Terminal mitlaufen lassen.
        viewModel.LogLines.CollectionChanged += OnLogLinesChanged;
    }

    private void OnLogLinesChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action != NotifyCollectionChangedAction.Add) return;

        // Nach dem Layout ans Ende scrollen, sonst existiert der Container noch nicht.
        Dispatcher.UIThread.Post(() =>
        {
            var list = this.FindControl<ListBox>("LogList");
            if (list?.ItemCount > 0) list.ScrollIntoView(list.ItemCount - 1);
        }, DispatcherPriority.Background);
    }

    private void OnExitClick(object? sender, RoutedEventArgs e) => Close();

    protected override void OnClosed(EventArgs e)
    {
        if (_vm != null)
        {
            _vm.LogLines.CollectionChanged -= OnLogLinesChanged;
            _vm.Shutdown();
            _vm = null;
        }
        base.OnClosed(e);
    }
}
