using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using HistoryWallEditTool.ControlsForData.MediaControllerLayout;
using System.Threading;

namespace HistoryWallEditTool.ControlsForData
{
    /// <summary>
    /// DetailDataMediaChild.xaml 的互動邏輯
    /// </summary>
    public partial class DetailDataMediaChild : UserControl
    {
        private readonly ImageBrush volumeEmpty =
            new ImageBrush(new BitmapImage(
                new Uri(@"pack://application:,,,/HistoryWallEditTool;component/Image/MediaController/soundEmpty.png")
                ));
        private readonly ImageBrush volumeDown =
            new ImageBrush(new BitmapImage(
                new Uri(@"pack://application:,,,/HistoryWallEditTool;component/Image/MediaController/soundDown.png")
                ));
        private readonly ImageBrush volumeMedium =
            new ImageBrush(new BitmapImage(
                new Uri(@"pack://application:,,,/HistoryWallEditTool;component/Image/MediaController/soundMedium.png")
                ));
        private readonly ImageBrush volumeUp =
            new ImageBrush(new BitmapImage(
                new Uri(@"pack://application:,,,/HistoryWallEditTool;component/Image/MediaController/soundUp.png")
                ));

        public delegate void MediaPlayInfoDelegate(int curPlayIndex);
        public event MediaPlayInfoDelegate MediaPlayInfoEvent;

        private MediaElement mediaElement = null;
        private DispatcherTimer refleshProgressValueTimer = new DispatcherTimer();
        private Image img;
        public string curMediaPath = "";
        public int curIndex = -1;

        public DetailDataMediaChild(int childIndex)
        {
            InitializeComponent();

            curIndex = childIndex;
        }

        #region 載影片或載圖
        public void LoadMedia(string mediaPath)
        {
            img = new Image();

            curMediaPath = mediaPath;
            img.Stretch = Stretch.Uniform;
            img.Source = GlobalFunction.GetMediaMap(curMediaPath);

            uxMainMedia.Children.Add(img);
        }

        public void LoadImage(string imgPath)
        {
            img = new Image();

            curMediaPath = imgPath;
            img.Stretch = Stretch.Uniform;
            img.Source = GlobalFunction.GetBitMap(curMediaPath, true, 275);

            uxControllerBoard.Visibility = Visibility.Collapsed;
            uxMainMedia.Children.Add(img);
        }
        #endregion

        private void MediaPlay()
        {
            if (mediaElement == null)
            {
                refleshProgressValueTimer.Interval = TimeSpan.FromMilliseconds(500);
                refleshProgressValueTimer.Tick += new EventHandler(refleshProgressValueTimer_Tick);

                mediaElement = new MediaElement();
                mediaElement.Source = new Uri(curMediaPath);
                mediaElement.Volume = (uxVolumeSlider.Percent / 100.0);
                mediaElement.IsMuted = false;
                mediaElement.LoadedBehavior = MediaState.Manual;
                mediaElement.MediaOpened += new RoutedEventHandler(mediaElement_MediaOpened);
                mediaElement.MediaEnded += new RoutedEventHandler(mediaElement_MediaEnded);
                mediaElement.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(mediaElement_MediaFailed);

                uxMainMedia.Children.Clear();
                uxMainMedia.Children.Add(mediaElement);
            }

            if (mediaElement != null)
            {
                mediaElement.Play();
                refleshProgressValueTimer.Start();
                this.Dispatcher.BeginInvoke(MediaPlayInfoEvent, DispatcherPriority.Background, curIndex);
            }
        }

        private void refleshProgressValueTimer_Tick(object sender, EventArgs e)
        {
            if (mediaElement.NaturalDuration.HasTimeSpan)
            {
                uxProgressSlider.Percent =
                       (mediaElement.Position.TotalSeconds / mediaElement.NaturalDuration.TimeSpan.TotalSeconds) * 100.0;
            }
        }

        private void mediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            uxPlayBtn.IsChecked = false;
            MediaStop();
        }

        private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {

        }

        private void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            uxPlayBtn.IsChecked = false;
            MediaStop();
        }

        private void MediaPause()
        {
            if (mediaElement == null)
            {
                return;
            }

            mediaElement.Pause();
            refleshProgressValueTimer.Stop();
        }

        private void MediaStop()
        {
            if (mediaElement == null)
            {
                return;
            }

            refleshProgressValueTimer.Stop();
            mediaElement.Stop();
            mediaElement.Position = TimeSpan.FromSeconds(0.0);
            uxProgressSlider.Percent = 0;
        }

        private void MediaMute(bool isMute)
        {
            if (mediaElement == null)
            {
                return;
            }

            mediaElement.IsMuted = isMute;
        }

        #region 操作面板
        #region play or pause
        private void uxPlayBtn_Checked(object sender, RoutedEventArgs e)
        {
            MediaPlay();
            Thread.Sleep(100);
        }

        private void uxPlayBtn_Unchecked(object sender, RoutedEventArgs e)
        {
            MediaPause();
        }
        #endregion

        #region stop
        private void uxStopBtn_Click(object sender, RoutedEventArgs e)
        {
            uxPlayBtn.IsChecked = false;
            MediaStop();
        }
        #endregion

        #region progress bar
        private void uxProgressSlider_OnValueChanged(object sender, ValueChangeEventArgs e)
        {
            if (mediaElement == null)
            {
                return;
            }
            uxPlayBtn.IsChecked = false;
            if (mediaElement.NaturalDuration.HasTimeSpan)
            {
                mediaElement.Position = TimeSpan.FromSeconds(
                mediaElement.NaturalDuration.TimeSpan.TotalSeconds * (e.percent / 100.0)
                );
            }
        }

        private void uxProgressSlider_OnSliderChangedEnd(object sender, EventArgs e)
        {
            uxPlayBtn.IsChecked = true;
        }
        #endregion

        #region mute
        private void uxVolumeBtn_Checked(object sender, RoutedEventArgs e)
        {
            MediaMute(false);
        }

        private void uxVolumeBtnn_Unchecked(object sender, RoutedEventArgs e)
        {
            MediaMute(true);
        }
        #endregion

        #region volume bar
        private void uxVolumeSlider_OnValueChanged(object sender, ValueChangeEventArgs e)
        {
            if (mediaElement == null)
            {
                return;
            }
            mediaElement.Volume = (e.percent / 100.0);

            if (mediaElement.Volume == 0.0)
            {
                uxVolumeBtn.UncheckedBrush = volumeEmpty;
            }
            else if (mediaElement.Volume > 0.0 && mediaElement.Volume <= 0.45)
            {
                uxVolumeBtn.UncheckedBrush = volumeDown;
            }
            else if (mediaElement.Volume > 0.45 && mediaElement.Volume <= 0.9)
            {
                uxVolumeBtn.UncheckedBrush = volumeMedium;
            }
            else
            {
                uxVolumeBtn.UncheckedBrush = volumeUp;
            }
        }
        #endregion
        #endregion

        #region internal function 
        //外部控制 : 停止播放影片
        internal void ExtraOperatorMediaStop()
        {
            uxPlayBtn.IsChecked = false;
            MediaStop();
        }

        //外部控制 : 將影片控制項移除，重新載入圖片
        internal void ReloadMediaThumbImage()
        {
            uxMainMedia.Children.Clear();
            if (mediaElement != null)
            {
                mediaElement.Source = null;
                mediaElement = null;
            }
            uxMainMedia.Children.Add(img);
        }
        #endregion
    }
}
