using BoFilTest.Domain;
using BoFilTest.Utils;
using System;
using System.Windows;
using System.Windows.Controls;
using Unity;

namespace BoFilTest.UI
{
    /// <summary>
    /// </summary>
    public partial class HardwareSettingsDialog : Window
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private const int FIRST_CURVE_HW_INDEX = 1;
        private const int SECOND_CURVE_HW_INDEX = 2;
        private HardwareControlWithFailSafe hardware;

        public static void Show(Window owner, IUnityContainer container)
        {
            try
            {
                var dialog = container.Resolve<HardwareSettingsDialog>();
                dialog.Owner = owner;
                dialog.ShowDialog();
            }
            catch (Exception e)
            {
                logger.Error(e, "Error while opening hardware settings");
                MessageBox.Show(owner, Translated.FromKey("ERROR_OPENING_HARDWARE_SETTINGS"),
                    Translated.FromKey("ERROR_TITLE"), MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        public HardwareSettingsDialog(HardwareControlWithFailSafe hardware)
        {
            InitializeComponent();
            Title = Translated.FromKey("HARDWARE_SETTINGS");
            AllTextBlocks.TranslateForRoot(Grid);

            try
            {
                this.hardware = hardware;
                LoadSettings();
            }
            catch (Exception)
            {
                this.hardware.Cleanup();
                throw;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            this.hardware.Cleanup();
        }

        private void SetLUTIndex(int value)
        {
            try
            {
                hardware.GasFlowMeasure.CalibrationCurveIndex = value;
            }
            catch (Exception e)
            {
                MessageBox.Show(this, Translated.FromKey("ERROR_SETTING_CALIBRATION_CURVE", e.Message),
                    Translated.FromKey("ERROR_TITLE"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LookupTable_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetLUTIndex(LookupTable.SelectedIndex);
        }

        private void LoadSettings()
        {
            LookupTable.SelectedIndex = hardware.GasFlowMeasure.CalibrationCurveIndex;
            LookupTable.SelectionChanged += LookupTable_SelectionChanged;
        }
    }
}
