using Autofac;
using Autofac.Features.ResolveAnything;
using Ion.Sdk.DemoApp.Framework;
using Ion.Sdk.Ici;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;

namespace Ion.Sdk.DemoApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application, IApplication
    {
        private void App_Startup(object sender, StartupEventArgs e)
        {
            // setup components
            Framework.Command.Use(this);
            BuildContainer(this);

            var window = container.Resolve<Views.MainWindow>();
            window.Show();
        }

        ILifetimeScope IApplication.BeginLifetimeScope() => BeginLifetimeScope();

        void IApplication.Log(Exception ex) => Log(ex);


        private static readonly TraceSource traceSource = new TraceSource("DemoApp");
        private static IContainer container;
        public static MessageHub Message { get; } = new MessageHub();
        public static ILifetimeScope BeginLifetimeScope() => container.BeginLifetimeScope();

        internal static void Log(Exception ex)
        {

            traceSource.TraceEvent(TraceEventType.Information, 0, "Information text.");
            traceSource.TraceEvent(TraceEventType.Warning, 0, "Warning text.");

            var text = new StringBuilder();

            text.AppendLine(ex.Message);
            if (ex.InnerException != null)
            {
                text.AppendLine("-<InnerException>-");
                text.AppendLine(ex.InnerException.Message);
            }

            text.AppendLine("-<StackTrace>-");
            text.AppendLine(ex.StackTrace);
            traceSource.TraceEvent(TraceEventType.Error, 0, text.ToString());
            traceSource.Flush();
        }

        private static void BuildContainer(App app)
        {
            var assembly = typeof(App).Assembly;


            var builder = new ContainerBuilder();

            builder.RegisterInstance(app).As<IApplication>();
            builder.RegisterAssemblyModules(assembly);

            var directory = Path.GetDirectoryName(assembly.Location);
            var assemblies = new List<Assembly>(from dll in Directory.EnumerateFiles(directory, "Ion.Sdk.DemoApp.*.dll")
                                                where Path.GetFileNameWithoutExtension(dll) != typeof(App).Assembly.GetName().Name
                                                select Assembly.LoadFrom(dll));

            builder.RegisterAssemblyModules(assemblies.ToArray());

            builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
            container = builder.Build();

        }



    }
}
