using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SPC.Kiosk.Common
{
    /// <summary>
    /// MediaPlayer.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MediaPlayer : UserControl
    {
        #region [  Members  ]
        private bool MoseDown = false;
        private Point MoseDownPosition;
        /// <summary>
        /// Noraml Bakcground 
        /// </summary>
        public static readonly DependencyProperty MediaFileProperty =
                 DependencyProperty.Register(nameof(MediaFile), typeof(string), typeof(MediaPlayer), new PropertyMetadata(string.Empty, new PropertyChangedCallback(OnMediaFilePropertyChanged)));
        /// <summary>
        /// OD Repeat Flag
        /// </summary>
        public static readonly DependencyProperty RepeatMediaProperty =
                 DependencyProperty.Register(nameof(RepeatMedia), typeof(bool), typeof(MediaPlayer), new PropertyMetadata(false));
        /// <summary>
        /// Play Media File (Path)
        /// </summary>
        public string MediaFile
        {
            get { return (string)GetValue(MediaFileProperty); }
            set { SetValue(MediaFileProperty, value); }
        }
        /// <summary>
        /// VOD Repeat Flag
        /// </summary>
        public bool RepeatMedia
        {
            get { return (bool)GetValue(RepeatMediaProperty); }
            set { SetValue(RepeatMediaProperty, value); }
        }
        #endregion Members

        #region [  Ctor / Method ]
        /// <summary>
        /// Ctor
        /// </summary>
        public MediaPlayer()
        {
            InitializeComponent();
            this.VideoMediaPlayer.LoadedBehavior = MediaState.Manual;
            this.VideoMediaPlayer.Loaded += VideoMediaPlayer_Loaded;
            this.VideoMediaPlayer.MediaEnded += VideoMediaPlayer_MediaEnded;
            this.VideoMediaPlayer.MouseUp += VideoMediaPlayer_MouseUp;
            this.VideoMediaPlayer.MouseDown += VideoMediaPlayer_MouseDown;
            this.VideoMediaPlayer.MouseLeave += VideoMediaPlayer_MouseLeave;
        }

        ~MediaPlayer()
        {
            this.VideoMediaPlayer.Loaded -= VideoMediaPlayer_Loaded;
            this.VideoMediaPlayer.MediaEnded -= VideoMediaPlayer_MediaEnded;
            this.VideoMediaPlayer.MouseUp -= VideoMediaPlayer_MouseUp;
            this.VideoMediaPlayer.MouseDown -= VideoMediaPlayer_MouseDown;
            this.VideoMediaPlayer.MouseLeave -= VideoMediaPlayer_MouseLeave;
        }

        /// <summary>
        /// VOD Restart
        /// </summary>
        public void Restart()
        {
            try
            {
                this.VideoMediaPlayer.Stop();
                this.VideoMediaPlayer.Position = TimeSpan.Zero;
                this.VideoMediaPlayer.Play();
            }
            catch 
            {
            }
        }
        /// <summary>
        /// VOD Stop
        /// </summary>
        public void Stop()
        {
            try
            {
                this.VideoMediaPlayer.Stop();

            }
            catch
            {
            }
        }
        /// <summary>
        /// VOD Play
        /// </summary>
        public void Play()
        {
            try
            {
                this.VideoMediaPlayer.Play();
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Play()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// VOD Pause
        /// </summary>
        public void Pause()
        {
            this.VideoMediaPlayer.Pause();
        }

        #endregion Ctor

        #region [ Events Create ]

        #region [ Make  RoutedEvent 'MouseClicked']
        /// <summary>
        /// MouseClicked Event
        /// </summary>
        public static readonly RoutedEvent MouseClickedEvent = EventManager.RegisterRoutedEvent(nameof(MouseClicked), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MediaPlayer));
        /// <summary>
        /// MouseClicked Routed Event Handler
        /// </summary>
        public event RoutedEventHandler MouseClicked
        {
            add { AddHandler(MouseClickedEvent, value); }
            remove { RemoveHandler(MouseClickedEvent, value); }
        }
        /// <summary>
        /// Raise MouseClicked Event
        /// </summary>
        private void RaiseMouseClickedEvent(object source)
        {
            RoutedEventArgs newEventArgs = new RoutedEventArgs(MediaPlayer.MouseClickedEvent, source);
            RaiseEvent(newEventArgs);
        }
        #endregion Make  RoutedEvent 'MouseClicked'

        #region [ Make  RoutedEvent 'MediaLoaded']
        /// <summary>
        /// MouseClicked Event
        /// </summary>
        public static readonly RoutedEvent MediaLoadedEvent = EventManager.RegisterRoutedEvent(nameof(MediaLoaded), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MediaPlayer));
        /// <summary>
        /// MouseClicked Routed Event Handler
        /// </summary>
        public event RoutedEventHandler MediaLoaded
        {
            add { AddHandler(MediaLoadedEvent, value); }
            remove { RemoveHandler(MediaLoadedEvent, value); }
        }
        /// <summary>
        /// Raise MouseClicked Event
        /// </summary>
        private void RaiseMediaOpend(object source)
        {
            RoutedEventArgs newEventArgs = new RoutedEventArgs(MediaPlayer.MediaLoadedEvent,source);
            RaiseEvent(newEventArgs);
        }
        #endregion Make  RoutedEvent 'MediaLoaded'

        #endregion Events Create

        #region [  Evnets Handler ]
        private static void OnMediaFilePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var target = d as MediaPlayer;
            target.VideoMediaPlayer.Source = string.IsNullOrEmpty((string)e.NewValue)
                                           ? null
                                           : new Uri((string)e.NewValue);
        }

        #region Mouse Events Handler
        private void VideoMediaPlayer_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (MoseDown)
            {
                if (Math.Abs(e.GetPosition(this).X - MoseDownPosition.X) > 50) MoseDown = false;
                if (Math.Abs(e.GetPosition(this).Y - MoseDownPosition.Y) > 50) MoseDown = false;
                if (MoseDown) RaiseMouseClickedEvent(this);
                MoseDown = false;
            }
        }

        private void VideoMediaPlayer_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MoseDown = true;
            MoseDownPosition = e.GetPosition(this);
        }

        private void VideoMediaPlayer_MouseLeave(object sender, MouseEventArgs e)
        {
            MoseDown = false;
        }
        #endregion

        #region Player Events Handler
        private void VideoMediaPlayer_Loaded(object sender, RoutedEventArgs e)
        {
            if (VideoMediaPlayer.Source is Uri)
            {

                if (RepeatMedia)
                {
                    if (VideoMediaPlayer.Source.AbsolutePath.ToLower().EndsWith(".gif"))
                    {

                        VideoMediaPlayer.Position = TimeSpan.FromMilliseconds(1);
                    }
                    VideoMediaPlayer.Play();
                }
                RaiseMediaOpend(e.OriginalSource);
            }
        }

        private void VideoMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            if (RepeatMedia)
            {
                if (VideoMediaPlayer.Source is Uri)
                {
                    if (VideoMediaPlayer.Source.AbsolutePath.ToLower().EndsWith(".gif"))
                    {

                        VideoMediaPlayer.Position = TimeSpan.FromMilliseconds(1);
                    }
                    else
                    {
                        VideoMediaPlayer.Position = TimeSpan.Zero;
                    }
                    VideoMediaPlayer.Play();
                }

            }
        }
        #endregion Player Events Handler

        #endregion Evnets Handler
    }
}
