using System.Windows;
using System.Windows.Controls;
using CtrEditor.ObjetosSim;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;

namespace CtrEditor.PopUps
{
    /// <summary>
    /// Interaction logic for LibraryWindow.xaml
    /// </summary>
    public partial class LibraryWindow : Window
    {
        public LibraryWindow()
        {
            InitializeComponent();

            // Aplicar configuraciones persistentes
            ApplyPersistedSettings();

            // Suscribirse al evento StateChanged para persistir cambios de estado
            StateChanged += LibraryWindow_StateChanged;
        }

        private void LibraryWindow_StateChanged(object sender, EventArgs e)
        {
            // Guardar el estado cuando cambia
            EstadoPersistente.Instance.LibraryWindow.IsMaximized = WindowState == WindowState.Maximized;
            EstadoPersistente.Instance.GuardarEstado();
        }

        private void ApplyPersistedSettings()
        {
            var settings = EstadoPersistente.Instance.LibraryWindow;

            // Asegurar que la ventana esté dentro de los límites de la pantalla
            var screenWidth = SystemParameters.WorkArea.Width;
            var screenHeight = SystemParameters.WorkArea.Height;

            if (settings.Left < 0 || settings.Left > screenWidth - 100)
                settings.Left = 100;
            if (settings.Top < 0 || settings.Top > screenHeight - 100)
                settings.Top = 100;

            if (settings.Width < 800 || settings.Width > screenWidth)
                settings.Width = 1200;
            if (settings.Height < 600 || settings.Height > screenHeight)
                settings.Height = 700;

            // Aplicar el estado de la ventana
            WindowState = settings.IsMaximized ? WindowState.Maximized : WindowState.Normal;
        }

        private void LibraryTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (DataContext is LibraryWindowViewModel viewModel)
            {
                if (e.NewValue is LibraryTreeNode selectedNode)
                {
                    viewModel.SelectedTreeNode = selectedNode;

                    // Si es una biblioteca (no directorio), establecer como biblioteca seleccionada
                    if (!selectedNode.IsDirectory && selectedNode.Library != null)
                    {
                        viewModel.SelectedLibrary = selectedNode.Library;
                    }
                }
            }
        }

        private void ObjectsTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (DataContext is LibraryWindowViewModel viewModel)
            {
                // Check if the selected item is an osBase object or an ObjectTypeGroup
                if (e.NewValue is osBase selectedObject)
                {
                    viewModel.SelectedObject = selectedObject;
                }
                else if (e.NewValue is ObjectTypeGroup typeGroup)
                {
                    // If a type group is selected, clear the selected object
                    viewModel.SelectedObject = null;
                }
                else
                {
                    viewModel.SelectedObject = null;
                }
            }
        }

        private void SelectAllObjects_Click(object sender, RoutedEventArgs e)
        {
            if (DataContext is LibraryWindowViewModel viewModel)
            {
                foreach (var item in viewModel.SelectableObjects)
                {
                    item.IsSelected = true;
                }
            }
        }

        private void UnselectAllObjects_Click(object sender, RoutedEventArgs e)
        {
            if (DataContext is LibraryWindowViewModel viewModel)
            {
                foreach (var item in viewModel.SelectableObjects)
                {
                    item.IsSelected = false;
                }
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Setup filter events after window is loaded
            if (DataContext is LibraryWindowViewModel viewModel)
            {
                ObjectFilter.FilterChanged += (s, args) => viewModel.OnFilterChanged(args.FilterViewModel);
                viewModel.SetObjectFilter(ObjectFilter);
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            // Guardar configuraciones de la ventana antes de cerrar
            SaveWindowSettings();
        }

        private void SaveWindowSettings()
        {
            var settings = EstadoPersistente.Instance.LibraryWindow;

            if (WindowState == WindowState.Normal)
            {
                settings.Width = ActualWidth;
                settings.Height = ActualHeight;
                settings.Left = Left;
                settings.Top = Top;
            }

            settings.IsMaximized = WindowState == WindowState.Maximized;

            EstadoPersistente.Instance.GuardarEstado();
        }
    }


}