using BoFilTest.Domain;
using BoFilTest.UI;
using BoFilTest.Utils;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Linq;
using NLog;
using Unity;
using System;

namespace BoFilTest.UI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class StartPage : Page
    {
        private readonly IUnityContainer container;
        private readonly EventBus eventBus;
        private readonly DataModel dataModel;

        public StartPage(IUnityContainer container, EventBus eventBus, DataModel dataModel)
        {
            dataModel.SetupNew();
            this.container = container;
            this.eventBus = eventBus;
            this.dataModel = dataModel;

            DataContext = new StartModel(dataModel);

            InitializeComponent();

            AllTextBlocks.TranslateForRoot(MainLayout);

            Loaded += StartPage_Loaded;
        }

        private void StartPage_Loaded(object sender, RoutedEventArgs e)
        {
            dataModel.SetupNew();
            ReloadViewModel();
        }

        StartModel Model { get => (StartModel)DataContext; }

        private void ReloadViewModel()
        {
            // This is a bit of a hack to reload all the data from the view model into the bound components
            // See: https://stackoverflow.com/questions/5157068/is-there-a-way-to-refresh-all-bindings-in-wpf
            // It's probably better if this refresh comes from the model
            Model.RefreshAll();
        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(container.Resolve<RunningPage>());
        }

        private void TextBox_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
        {
            if (sender is TextBox textBox)
                textBox.SelectAll();
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(Window.GetWindow(this), Translated.FromKey("LOAD_CONFIGURED_DEFAULTS"),
                Translated.FromKey("LOAD_CONFIGURED_DEFAULTS_TITLE"), MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            dataModel.LoadConfiguredDefaults();
            ReloadViewModel();
        }

        private void HardwareSettingsButton_Click(object sender, RoutedEventArgs e)
        {
            HardwareSettingsDialog.Show(Window.GetWindow(this), container);
        }
    }
}
