using System;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SilverlightMediaFramework.Core;
using Microsoft.SilverlightMediaFramework.Utilities.Extensions;
using Microsoft.SilverlightMediaFramework.Plugins.Primitives;
using Microsoft.Web.Media.SmoothStreaming;

namespace LiveDvrSmoothStreaming
{
    public class DvrSMFPlayer : SMFPlayer
    {
        SmoothStreamingMediaElement ssme;


        public void LogIt(object obj)
        {
            HtmlWindow window = HtmlPage.Window;
            var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");
            if (isConsoleAvailable)
            {
                var console = (window.Eval("console.log") as ScriptObject);
                if (console != null)
                {
                    console.InvokeSelf(obj);
                }
            }
        }


        protected override void OnMediaPluginLoaded()
        {
            base.OnMediaPluginLoaded();

            ssme = ActiveMediaPlugin.VisualElement as SmoothStreamingMediaElement;

            if (ssme != null)
            {
                ssme.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(SmoothPlayer_MediaFailed);
                ssme.SmoothStreamingErrorOccurred += new EventHandler<SmoothStreamingErrorEventArgs>(SmoothPlayer_SmoothStreamingErrorOccurred);
                ssme.ClipError += new EventHandler<ClipEventArgs>(SmoothPlayer_ClipError);
            }

        }
        protected override void OnMediaPluginLoadFailed()
        {
            reportError("Media Plugin Did Not Load");
        }

        public void reportError(String errorMessage)
        {
            LogIt(errorMessage);
            MessageBox.Show(errorMessage);
        }

        void SmoothPlayer_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            reportError("Media Error: " + e.ErrorException.Message);
        }

        void SmoothPlayer_SmoothStreamingErrorOccurred(object sender, SmoothStreamingErrorEventArgs e)
        {
            reportError("Streaming Error: " + e.ErrorMessage);

        }

        void SmoothPlayer_ClipError(object sender, ClipEventArgs e)
        {
            reportError("Clip Error: " + e.Context.CurrentClipState.ToString());
        }

    }

}
