using System.Windows;
using CtrEditor.Models;
using CtrEditor.ObjetosSim;
using Xceed.Wpf.Toolkit.PropertyGrid;

namespace CtrEditor.PopUps
{
    public partial class RenameImageWindow : Window
    {
        public ImageData ImageData { get; private set; }
        public bool IsOkClicked { get; private set; }

        public RenameImageWindow(string originalName, ImageData imageData = null)
        {
            InitializeComponent();

            OriginalNameTextBlock.Text = originalName;

            // Crear o usar ImageData existente
            ImageData = imageData ?? new ImageData
            {
                FileName = originalName,
                CustomName = string.Empty,
                Etiquetas = string.Empty
            };

            // Configurar PropertyGrid
            PropertyGridControl.SelectedObject = ImageData;

            Focus();
        }

        private void TagEditorButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Obtener el MainWindow para acceder a todos los objetos
                var mainWindow = Application.Current.Windows
                    .OfType<MainWindow>()
                    .FirstOrDefault();

                if (mainWindow?.DataContext is MainViewModel mainViewModel)
                {
                    // Para ImageData, crear un osBase temporal para usar el editor
                    var tempOsBase = new osTextPlate();
                    tempOsBase.Etiquetas = ImageData.Etiquetas;

                    var tagEditor = new TagEditorWindow(tempOsBase, mainViewModel.ObjetosSimulables, mainViewModel._imageDataDictionary);
                    tagEditor.Owner = this;

                    if (tagEditor.ShowDialog() == true)
                    {
                        // Actualizar ImageData con las nuevas etiquetas
                        ImageData.Etiquetas = tempOsBase.Etiquetas;

                        // Forzar actualización del PropertyGrid
                        PropertyGridControl.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error al abrir el editor de etiquetas: {ex.Message}",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OkButton_Click(object sender, RoutedEventArgs e)
        {
            IsOkClicked = true;
            DialogResult = true;
            Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            IsOkClicked = false;
            DialogResult = false;
            Close();
        }
    }
}