using Nodify.Interactivity;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace Nodify.Calculator
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            EditorGestures.Mappings.Editor.Cutting.Unbind();

            EventManager.RegisterClassHandler(
                    typeof(UIElement),
                    Keyboard.PreviewGotKeyboardFocusEvent,
                    (KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus);

            Closing += MainWindow_Closing;
        }

        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            var result = MessageBox.Show(
                "Do you want to save the project before closing?",
                "Save Project",
                MessageBoxButton.YesNoCancel,
                MessageBoxImage.Question);

            if (result == MessageBoxResult.Cancel)
            {
                e.Cancel = true;
                return;
            }

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    if (DataContext is ApplicationViewModel appVm && appVm.Editors.Count > 0)
                    {
                        var firstEditor = appVm.Editors.First();
                        GraphSerializer.Save(firstEditor.Calculator);
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show($"Failed to save: {ex.Message}", "Save Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            Title = e.NewFocus.ToString();
        }
    }
}
