using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using NavisworksTransport.Core.Services;
using NavisworksTransport.UI.WPF.ViewModels;
using NavisworksTransport.Core.Models;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 时标设置对话框
    /// </summary>
    public partial class TimeTagDialog : Window
    {
        private TimeTagViewModel _viewModel;

        public TimeTagDialog(TimeTagService timeTagService, PathRoute route)
        {
            InitializeComponent();
            
            try
            {
                _viewModel = new TimeTagViewModel(timeTagService, route);
                DataContext = _viewModel;
            }
            catch (Exception ex)
            {
                LogManager.Error($"时标对话框初始化失败: {ex.Message}");
                MessageBox.Show($"初始化失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                throw;
            }
        }

        /// <summary>
        /// 关闭按钮
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 距离滑块预览鼠标左键按下时开始拖动
        /// </summary>
        private void DistanceSlider_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 开始拖动，此时不更新源
        }

        /// <summary>
        /// 距离滑块预览鼠标左键松开时结束拖动并更新源
        /// </summary>
        private void DistanceSlider_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (sender is Slider slider)
            {
                // 鼠标松开时更新绑定源，触发重新排序
                var binding = slider.GetBindingExpression(Slider.ValueProperty);
                binding?.UpdateSource();
            }
        }
    }

    /// <summary>
    /// 反向布尔到可见性转换器（false时Visible，true时Collapsed）
    /// </summary>
    public class InverseBooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool boolValue)
            {
                return boolValue ? Visibility.Collapsed : Visibility.Visible;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Visibility visibility)
            {
                return visibility != Visibility.Visible;
            }
            return false;
        }
    }
}
