using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.IO;

namespace SilverlightMediaPlayer
{
    public partial class MediaPlayer : UserControl
    {
        private bool isPlaying = false;

        private bool inRenderingEvent = false;
        private string fileDownloadUrl = null;
        private string fileUploadUrl = null;
        public string fileServiceUrl;
        public string fileListUrl;
        private string playingFileName = "";
        FileInfo playingLocalFile = null;

        public MediaPlayer()
        {
            InitializeComponent();
            System.Windows.Browser.HtmlPage.RegisterScriptableObject("MediaPlayer", this);
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
            Application.Current.Host.Content.FullScreenChanged += new EventHandler(Content_FullScreenChanged);

            playBtnContent = playBtn.Content;
            this.ableToPlay(false);
        }
        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            inRenderingEvent = true;

            TimeSpan duration = media.NaturalDuration.TimeSpan;
            if (duration.TotalSeconds > 0)
            {
                videoSlider.Value = media.Position.TotalSeconds / duration.TotalSeconds;
                this.currentTimeBlock.Text = formatTime(media.Position);
                //timeLine.Content = video_Slider.Value;
            }
            inRenderingEvent = false;

        }

        private static string formatTime(TimeSpan ts)
        {
            return string.Format("{0:00}:{1:00}", ts.Hours * 60 + ts.Minutes, ts.Seconds);
        }

        private void Content_FullScreenChanged(object sender, EventArgs e)
        {
            resetMediaSize();
        }
        private string GetParam(string p)
        {
            if (App.Current.Resources[p] != null)
                return App.Current.Resources[p].ToString();
            else
                return string.Empty;
        }
        private void StopMedia(object sender, RoutedEventArgs e)
        {
            this.media.Stop();
            isPlaying = false;
            playBtn.IsChecked = false;
 
        }

        private void PauseMedia(object sender, RoutedEventArgs e)
        {
            media.Pause();
        }

        private void PlayMedia(object sender, RoutedEventArgs e)
        {
            isPlaying = !(bool)playBtn.IsChecked;

            _PlayMedia();
        }
        private object playBtnContent;
        private void _PlayMedia()
        {
            stopBtn.IsEnabled = true;

            if (!isPlaying)
            {
                media.Play();
                isPlaying = true;
                playBtn.Content = "Pause";
            }
            else
            {
                media.Pause();
                isPlaying = false;
                playBtn.Content = "Resume";
            }
        }

        private void videoSlider_ValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
        {
            if (inRenderingEvent)
            {
                return;
            }
            videoSeek( videoSlider.Value);
          
			
        	// TODO: Add event handler implementation here.
        }

        private void videoSeek(double p)
        {
            if (inRenderingEvent)
            {
                return;
            }
            TimeSpan duration =  media.NaturalDuration.TimeSpan;
            int newSecond = (int)(duration.TotalSeconds * p);
            media.Position = new TimeSpan(0, 0, newSecond);
        }

        private void btnFull_Click(object sender, RoutedEventArgs e)
        {
            var content = Application.Current.Host.Content;
            if (content.IsFullScreen)
            {
                media.Height = 300;
            }
            else
            {
                media.Height = Double.NaN;
            }
            content.IsFullScreen = !content.IsFullScreen;
            
            //new MessageChildWindow((int)MessageChildWindow.mode.ERROR, "Not Implemented").Show();
        }



        private void _playFile(bool autoPlay)
        {
            media.AutoPlay = autoPlay;
            isPlaying = autoPlay;
            playBtn.IsChecked = isPlaying;
            stopBtn.IsEnabled = true;
        }
        [System.Windows.Browser.ScriptableMember]        
        public void SilverlightFunctionPlay(string url, string name) {

            this.media.Source = new Uri(url);
            playingFileName = name;
            _playFile(true);
        }



        private void resetMediaSize()
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                mediaRow.Height = new GridLength(1, GridUnitType.Star);
                mediaCol.Width = new GridLength(1, GridUnitType.Star);
            }
            else
            {
                mediaRow.Height = new GridLength(1, GridUnitType.Auto);
                mediaCol.Width = new GridLength(1, GridUnitType.Auto);
            }
        }

        private void media_MediaOpened(object sender, RoutedEventArgs e)
        {
            resetMediaSize();
            fileInfo.Content = "Playing " + playingFileName;
            totalTimeBlock.Text = formatTime(media.NaturalDuration.TimeSpan);
            media.BufferingProgressChanged += new RoutedEventHandler(media_BufferingProgressChanged);
            ableToPlay(true);
        }

        private void ableToPlay(bool b)
        {
            if (b)
            {
                timelineGrid.Visibility = Visibility.Visible;
                playBtn.IsEnabled = true;
            }
            else
            {
                timelineGrid.Visibility = Visibility.Collapsed;
                playBtn.IsEnabled = false;
                stopBtn.IsEnabled = false;
            }
        }

        void media_BufferingProgressChanged(object sender, RoutedEventArgs e)
        {
            //bufferProgress.Value = media.BufferingProgress;            
        }

        private void media_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            fileInfo.Content = this.media.Source;
            ableToPlay(false);
            
        }


    }
}
