using System;
using System.Windows;
using System.Windows.Browser;

namespace ynhtm.Upfile
{
    public partial class App : Application
    {
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new Main(e.InitParams);
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                var s = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                s = s.Replace('"', '\'').Replace("\r\n", @"\n");
                HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + s + "\");");
            }
            catch { }
        }
    }
}
