using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using MessageBox = System.Windows.MessageBox;
// 明确使用 WPF 的 OpenFileDialog，避免与 Windows Forms 冲突
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;

namespace VideoConcat.Views
{
    /// <summary>
    /// VideoPreviewWindow.xaml 的交互逻辑
    /// </summary>
    public partial class VideoPreviewWindow : Window
    {
        private DispatcherTimer _timer;
        private bool _isPlaying = false;

        public VideoPreviewWindow()
        {
            InitializeComponent();
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(500);
            _timer.Tick += Timer_Tick;
        }

        public void LoadVideo(string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath))
                {
                    MessageBox.Show("视频文件路径为空！", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!File.Exists(filePath))
                {
                    MessageBox.Show($"视频文件不存在：\n{filePath}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 重置播放器状态
                VideoPlayer.Stop();
                _isPlaying = false;
                _timer?.Stop();
                
                // 设置文件名
                FileNameText.Text = Path.GetFileName(filePath);
                
                // 创建 URI（使用绝对路径）
                string fullPath = Path.GetFullPath(filePath);
                // Uri 构造函数会自动处理本地文件路径
                Uri videoUri = new Uri(fullPath, UriKind.Absolute);
                
                // 加载视频（MediaOpened 事件已在 XAML 中定义，这里直接设置源）
                VideoPlayer.Source = videoUri;
                
                // 由于 MediaOpened 事件在 XAML 中已定义，视频加载完成后会自动触发
                // 如果需要立即播放，可以在 MediaOpened 事件处理中处理
            }
            catch (UriFormatException ex)
            {
                MessageBox.Show($"视频文件路径格式错误：\n{ex.Message}\n\n文件路径：{filePath}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载视频失败：\n{ex.Message}\n\n文件路径：{filePath}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void VideoPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            try
            {
                if (VideoPlayer.NaturalDuration.HasTimeSpan)
                {
                    TotalTimeText.Text = FormatTime(VideoPlayer.NaturalDuration.TimeSpan);
                    ProgressBar.Maximum = VideoPlayer.NaturalDuration.TimeSpan.TotalSeconds;
                }
                
                // 自动开始播放
                if (!_isPlaying)
                {
                    VideoPlayer.Play();
                    _isPlaying = true;
                    PlayPauseButton.Content = "暂停";
                    _timer?.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"媒体打开后处理失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        private void VideoPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            _isPlaying = false;
            PlayPauseButton.Content = "播放";
            VideoPlayer.Position = TimeSpan.Zero;
            _timer.Stop();
        }

        private void PlayPauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isPlaying)
            {
                VideoPlayer.Pause();
                _isPlaying = false;
                PlayPauseButton.Content = "播放";
            }
            else
            {
                VideoPlayer.Play();
                _isPlaying = true;
                PlayPauseButton.Content = "暂停";
                _timer.Start();
            }
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            VideoPlayer.Stop();
            _isPlaying = false;
            PlayPauseButton.Content = "播放";
            _timer.Stop();
            CurrentTimeText.Text = "00:00";
            ProgressBar.Value = 0;
        }

        private void OpenFileButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "视频文件|*.mp4;*.avi;*.mkv;*.mov;*.wmv|所有文件|*.*",
                Title = "选择视频文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                LoadVideo(openFileDialog.FileName);
            }
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (VideoPlayer.NaturalDuration.HasTimeSpan)
            {
                var currentTime = VideoPlayer.Position;
                CurrentTimeText.Text = FormatTime(currentTime);
                ProgressBar.Value = currentTime.TotalSeconds;
            }
        }

        private string FormatTime(TimeSpan timeSpan)
        {
            return $"{(int)timeSpan.TotalMinutes:D2}:{timeSpan.Seconds:D2}";
        }

        protected override void OnClosed(EventArgs e)
        {
            _timer?.Stop();
            VideoPlayer?.Close();
            base.OnClosed(e);
        }
    }
}

