using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
//using Installables.All;
//using Yaulw.Other;
using System.IO;
using System.Reflection;

namespace MSLMobile
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Main Application Object
        /// </summary>
        public App()
        {
            // Make sure all embedded Assemblies get loaded
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        #region Application Startup N' Exit

        /// <summary>
        /// Application_Startup
        /// </summary>        
        private void Application_Startup(object sender, StartupEventArgs e)
        {

        }

        /// <summary>
        /// Application_Exit
        /// </summary>
        private void Application_Exit(object sender, ExitEventArgs e)
        {

        }

        #endregion

        #region Unhandled Expections! IMP - Show WinForm and Log

        /// <summary>
        /// * Generic Unhandled Exception Handler *
        /// Handles all unhandled Exceptions for the Entire AppDomain.
        /// First Show a Window Message Box, so that we can for sure capture the message
        /// Second Log it
        /// </summary>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;

            // Exeption to capture error information
            string exceptionMessage = "Setup will exit.\n";
            exceptionMessage += ex.Message + "\n\n";
            if (!String.IsNullOrEmpty(ex.StackTrace))
                exceptionMessage += ex.StackTrace.Substring(0, 880) + "\n\n";
            if (!String.IsNullOrEmpty(ex.InnerException.Message))
                exceptionMessage += ex.InnerException.Message + "\n\n";
            if (!String.IsNullOrEmpty(ex.Source))
                exceptionMessage += ex.Source + "\n\n";

            // Show Message Box First - Guaranteed to work (Polite Exception Message)
            MessageBox.Show(exceptionMessage, "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        #endregion

        #region Application Multi-File Assembly Handling

        /// <summary>
        /// A way to embed multiple dlls into one exe:
        /// http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
        /// </summary>
        /// <returns>a loaded assembly if found, null otherwise</returns>
        static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            String AssemblyToLookFor = (new AssemblyName(args.Name).Name + ".dll").ToLower();

            // Note: due to the nature of click once, we must always
            // load the signed assembly not the unsigned
            //string[] parts = AssemblyToLookFor.Split('.');
            //AssemblyToLookFor = parts[0] + ".signed.dll";

            string[] resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            foreach (string s in resources)
            {
                if (s.ToLower().EndsWith(AssemblyToLookFor))
                {
                    var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(s);
                    if (stream != null)
                    {
                        using (stream)
                        {
                            Byte[] assemblyData = new Byte[stream.Length];
                            stream.Read(assemblyData, 0, assemblyData.Length);
                            return Assembly.Load(assemblyData);
                        }
                    }
                }
            }
            return null;
        }

        #endregion

    }
}
