using BoFilTest.Domain;
using BoFilTest.UI;
using BoFilTest.Utils;
using NLog;
using System;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Markup;
using Unity;

namespace BoFilTest
{
    /// <summary>
    /// Main entry point. Starts the update.
    /// </summary>
    public partial class App : Application
    {
        public static string ReadVersion()
        {
            try
            {
                return File.ReadAllText("version.config").Trim();
            }
            catch(Exception)
            {
                return "";
            }
        }
        
        public void BootApplication(object sender, StartupEventArgs eventArgs)
        {
            try
            {
                StartUI();
            }
            catch (Exception e)
            {
                MessageBox.Show(Translated.FromKey("STARTUP_ERROR", e.Message), Translated.FromKey("ERROR_TITLE"));
                Application.Current.Shutdown();
            }
        }

        private static void StartUI()
        {
            var logger = StartLogging();
            var version = ReadVersion();
            logger.Info("Application version is \"{0}\"", version);

            var unity = new UnityContainer();
            unity.AddExtension(new Diagnostic());
            unity.RegisterSingleton<EventBus>();
            unity.RegisterInstance(Utils.Configuration.PrepareAndLoad());
            unity.RegisterSingleton<StartPage>();
            unity.RegisterSingleton<RunningPage>();
            unity.RegisterSingleton<EndPage>();
            unity.RegisterType<HardwareControlWithFailSafe>();
            unity.RegisterType<HardwareSettingsDialog>();

            var config = unity.Resolve<Utils.Configuration>();
            var eventBus = unity.Resolve<EventBus>();
            unity.RegisterInstance(new DataModel(eventBus, config, version));
            var beeper = new Beeper(eventBus);

            TestLogging.Setup(eventBus);

            SetupCurrentCultureForFrameworkElements();            

            // Show the main window
            unity.Resolve<MainWindow>().Show();
        }

        // Required, so that WPF XAML number form fields use current culture instead instead of en-US
        // See https://serialseb.com/blog/2007/04/03/wpf-tips-1-have-all-your-dates-times/
        private static void SetupCurrentCultureForFrameworkElements()
        {
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),
                new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
        }

        private static Logger StartLogging()
        {
            Logging.Configure();
            var log = LogManager.GetCurrentClassLogger();
            log.Info("Starting BoFilTest application");
            return log;
        }
    }
}
