using Avalonia.Controls;
using Avalonia.Interactivity;
using GsaEditor.ViewModels;

namespace GsaEditor.Views;

public partial class MainWindow : Window
{
    private bool _forceClose;

    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);

        if (DataContext is MainWindowViewModel vm)
        {
            vm.SetWindow(this);
        }
    }

    private void TreeView_SelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (DataContext is MainWindowViewModel vm && sender is TreeView tree)
        {
            vm.SelectedNode = tree.SelectedItem as EntryTreeNodeViewModel;
        }
    }

    protected override async void OnClosing(WindowClosingEventArgs e)
    {
        base.OnClosing(e);

        if (_forceClose) return;

        if (DataContext is MainWindowViewModel vm && vm.IsDirty)
        {
            e.Cancel = true;
            var confirmed = await Helpers.Dialogs.ConfirmAsync(this, "Unsaved Changes",
                "You have unsaved changes. Close without saving?");
            if (confirmed)
            {
                _forceClose = true;
                Close();
            }
        }
    }
}
