using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Markup;
using DebugToolInstrumentInterface;

namespace QFDT;

public partial class Option : System.Windows.Controls.UserControl, IComponentConnector
{
	public delegate void SaveConfiguration(Factory_Debug_Cofiguration configuration, bool createDefault);

	public delegate void LanguageChange(string culuture);

	public SaveConfiguration SaveConfigurationCB;

	private LanguageChange LanguageChangeCB;

	private Factory_Debug_Cofiguration m_configuration;

	private void InitDriverComboBox(System.Windows.Controls.ComboBox cbx)
	{
		cbx.Items.Clear();
		cbx.Items.Add(TEDriverType.gpib_32);
		cbx.Items.Add(TEDriverType.visa32);
		cbx.SelectedIndex = 0;
	}

	public Option()
	{
		InitializeComponent();
		InitDriverComboBox(cbxPSDriver);
		InitDriverComboBox(cbxSpecAnDriver);
		InitDriverComboBox(cbxSiggenDriver);
	}

	public void SetLanguageCB(LanguageChange cb)
	{
		LanguageChangeCB = cb;
	}

	public void SetLanguage(string culture)
	{
		ResourceDictionary resourceDictionary = new ResourceDictionary();
		string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
		try
		{
			resourceDictionary.Source = new Uri(baseDirectory + ".\\Resources\\Dictionary_" + culture + ".xaml", UriKind.Absolute);
		}
		catch
		{
			resourceDictionary.Source = new Uri(baseDirectory + ".\\Resources\\Dictionary_en-US.xaml", UriKind.Absolute);
		}
		base.Resources.MergedDictionaries.Clear();
		base.Resources.MergedDictionaries.Add(resourceDictionary);
	}

	public void SetOptions(ref Factory_Debug_Cofiguration configuration, List<string> AllTabName)
	{
		m_configuration = configuration;
		Product_Configuration_Folder.Text = m_configuration.Product_Configuration_Folder;
		HLOS_Command_Path.Text = m_configuration.HLOS_XML_Path;
		UpgradePath.Text = m_configuration.UpdateService.UpgradePath;
		if (m_configuration.UpdateService.AutoUpdate == 1)
		{
			CBAutoUpgrade.IsChecked = true;
		}
		SetLanguage(m_configuration.Language);
		InitEquipComponentGroups<IPowerSupply>(cbxPSDriver, ps_dll_combo, ps_resource_name, ps_gpib, ps_visa, m_configuration.PowerSupply);
		InitEquipComponentGroups<ISpectrumAnalyzer>(cbxSpecAnDriver, specan_dll_combo, specan_resource_name, specan_gpib, specan_visa, m_configuration.SpectrumAnalyzer);
		InitEquipComponentGroups<ISignalGenerator>(cbxSiggenDriver, siggen_dll_combo, siggen_resource_name, siggen_gpib, siggen_visa, m_configuration.SignalGenerator);
		if (AllTabName != null)
		{
			tabList.SelectionMode = System.Windows.Controls.SelectionMode.Multiple;
			for (int i = 0; i < AllTabName.Count; i++)
			{
				tabList.Items.Add(AllTabName[i]);
			}
			for (int i = 0; i < m_configuration.UI.ShowOnly.Tab.Length; i++)
			{
				for (int j = 0; j < tabList.Items.Count; j++)
				{
					if ((string)tabList.Items[j] == m_configuration.UI.ShowOnly.Tab[i])
					{
						tabList.SelectedItems.Add(tabList.Items[j]);
						break;
					}
				}
			}
		}
		if (m_configuration.UI.ShowAll == 1)
		{
			cbShowAll.IsChecked = true;
		}
		if (m_configuration.Device_Detection_Keywords == null || m_configuration.Device_Detection_Keywords.Keyword.Length <= 0)
		{
			return;
		}
		for (int i = 0; i < m_configuration.Device_Detection_Keywords.Keyword.Length; i++)
		{
			DiagKeyWords.Text += m_configuration.Device_Detection_Keywords.Keyword[i];
			if (i != m_configuration.Device_Detection_Keywords.Keyword.Length - 1)
			{
				DiagKeyWords.Text += ",";
			}
		}
	}

	private void bnSave_Click(object sender, RoutedEventArgs e)
	{
		m_configuration.Language = MainWindow.EnumToLangStr((Language)cboLanguageSelector.SelectedIndex);
		if (CBAutoUpgrade.IsChecked == true)
		{
			m_configuration.UpdateService.AutoUpdate = 1;
		}
		else
		{
			m_configuration.UpdateService.AutoUpdate = 0;
		}
		if (cbShowAll.IsChecked == true)
		{
			m_configuration.UI.ShowAll = 1;
		}
		else
		{
			m_configuration.UI.ShowAll = 0;
		}
		m_configuration.HLOS_XML_Path = HLOS_Command_Path.Text;
		m_configuration.Product_Configuration_Folder = Product_Configuration_Folder.Text;
		m_configuration.UpdateService.UpgradePath = UpgradePath.Text;
		m_configuration.PowerSupply.TE_type = ((ps_resource_name.SelectedValue != null) ? ps_resource_name.SelectedValue.ToString() : "");
		m_configuration.PowerSupply.driverType = ((cbxPSDriver.SelectedItem != null) ? ((TEDriverType)cbxPSDriver.SelectedItem).ToString() : "");
		m_configuration.PowerSupply.gpib = ps_gpib.Text;
		m_configuration.PowerSupply.visa32_desc = ps_visa.Text;
		m_configuration.PowerSupply.Resource = m_configuration.PowerSupply.getResource();
		m_configuration.PowerSupply.RelativePath = ((ps_dll_combo.SelectedValue != null) ? ps_dll_combo.SelectedValue.ToString() : "");
		m_configuration.SignalGenerator.TE_type = ((siggen_resource_name.SelectedValue != null) ? siggen_resource_name.SelectedValue.ToString() : "");
		m_configuration.SignalGenerator.driverType = ((cbxSiggenDriver.SelectedItem != null) ? ((TEDriverType)cbxSiggenDriver.SelectedItem).ToString() : "");
		m_configuration.SignalGenerator.gpib = siggen_gpib.Text;
		m_configuration.SignalGenerator.visa32_desc = siggen_visa.Text;
		m_configuration.SignalGenerator.Resource = m_configuration.SignalGenerator.getResource();
		m_configuration.SignalGenerator.RelativePath = ((siggen_dll_combo.SelectedValue != null) ? siggen_dll_combo.SelectedValue.ToString() : "");
		m_configuration.SpectrumAnalyzer.TE_type = ((specan_resource_name.SelectedValue != null) ? specan_resource_name.SelectedValue.ToString() : "");
		m_configuration.SpectrumAnalyzer.driverType = ((cbxSpecAnDriver.SelectedItem != null) ? ((TEDriverType)cbxSpecAnDriver.SelectedItem).ToString() : "");
		m_configuration.SpectrumAnalyzer.gpib = specan_gpib.Text;
		m_configuration.SpectrumAnalyzer.visa32_desc = specan_visa.Text;
		m_configuration.SpectrumAnalyzer.Resource = m_configuration.SpectrumAnalyzer.getResource();
		m_configuration.SpectrumAnalyzer.RelativePath = ((specan_dll_combo.SelectedValue != null) ? specan_dll_combo.SelectedValue.ToString() : "");
		if (DiagKeyWords.Text.Length >= 0)
		{
			string[] array = DiagKeyWords.Text.Split(',');
			m_configuration.Device_Detection_Keywords = new Device_Detection_Keyword();
			m_configuration.Device_Detection_Keywords.Keyword = new string[array.Length];
			for (int i = 0; i < array.Length; i++)
			{
				m_configuration.Device_Detection_Keywords.Keyword[i] = array[i];
			}
		}
		if (SaveConfigurationCB != null)
		{
			SaveConfigurationCB(m_configuration, createDefault: false);
		}
	}

	private void bnDefault_Click(object sender, RoutedEventArgs e)
	{
		if (Option_Tab.SelectedIndex == 2)
		{
			Factory_Debug_Cofiguration factory_Debug_Cofiguration = new Factory_Debug_Cofiguration();
			InitEquipComponentGroups<IPowerSupply>(cbxPSDriver, ps_dll_combo, ps_resource_name, ps_gpib, ps_visa, factory_Debug_Cofiguration.PowerSupply);
			InitEquipComponentGroups<ISpectrumAnalyzer>(cbxSpecAnDriver, specan_dll_combo, specan_resource_name, specan_gpib, specan_visa, factory_Debug_Cofiguration.SpectrumAnalyzer);
			InitEquipComponentGroups<ISignalGenerator>(cbxSiggenDriver, siggen_dll_combo, siggen_resource_name, siggen_gpib, siggen_visa, factory_Debug_Cofiguration.SignalGenerator);
		}
	}

	private void cboLanguageSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		SetLanguage(MainWindow.EnumToLangStr((Language)cboLanguageSelector.SelectedIndex));
		if (LanguageChangeCB != null)
		{
			LanguageChangeCB(MainWindow.EnumToLangStr((Language)cboLanguageSelector.SelectedIndex));
		}
		bnSave_Click(null, null);
	}

	private void PCF_Folder_Browser_Click(object sender, RoutedEventArgs e)
	{
		using FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
		folderBrowserDialog.Description = "Select QFDT product folder";
		if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
		{
			Product_Configuration_Folder.Text = folderBrowserDialog.SelectedPath;
			m_configuration.Product_Configuration_Folder = Product_Configuration_Folder.Text;
			bnSave_Click(null, null);
		}
	}

	private void HLOS_Path_Browser_Click(object sender, RoutedEventArgs e)
	{
		OpenFileDialog openFileDialog = new OpenFileDialog();
		openFileDialog.InitialDirectory = "c:\\";
		openFileDialog.Filter = "HLOS Command Path files (*.xml)|*.xml|All files (*.*)|*.*";
		openFileDialog.FilterIndex = 1;
		openFileDialog.RestoreDirectory = true;
		if (openFileDialog.ShowDialog() == DialogResult.OK)
		{
			HLOS_Command_Path.Text = openFileDialog.FileName;
			m_configuration.HLOS_XML_Path = HLOS_Command_Path.Text;
			bnSave_Click(null, null);
		}
	}

	private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		if (Option_Tab.SelectedIndex == 0)
		{
			ShowBottomButtons(bShow: false);
		}
		else if (Option_Tab.SelectedIndex == 1)
		{
			ShowBottomButtons(bShow: false);
		}
		else if (Option_Tab.SelectedIndex == 2)
		{
			ShowBottomButtons(bShow: true);
		}
		else
		{
			ShowBottomButtons(bShow: true);
		}
	}

	private void ShowBottomButtons(bool bShow)
	{
		BottomPanel.IsEnabled = bShow;
	}

	private void DiagKeyWords_TextChanged(object sender, TextChangedEventArgs e)
	{
	}

	private bool parseResourceString(string ResStr, out string name, out string gpibAddr)
	{
		try
		{
			string[] array = ResStr.Split(',');
			name = array[0];
			gpibAddr = array[1];
			return true;
		}
		catch
		{
			name = null;
			gpibAddr = null;
			return false;
		}
	}

	public void InitSpecialComboBox(object obj, List<string> itemList, string valueLoadFromCfg)
	{
		if (!(obj is System.Windows.Controls.ComboBox comboBox))
		{
			return;
		}
		comboBox.Items.Clear();
		foreach (string item in itemList)
		{
			string newItem = item.ToString();
			comboBox.Items.Add(newItem);
		}
		if (valueLoadFromCfg != null && valueLoadFromCfg != "")
		{
			if (!itemList.Exists((string r) => r == valueLoadFromCfg))
			{
				comboBox.Items.Add(valueLoadFromCfg);
			}
			comboBox.SelectedValue = valueLoadFromCfg;
		}
	}

	public List<string> getSupportedList(string assemblyPath)
	{
		List<string> list = new List<string>();
		try
		{
			string fullPath = Path.GetFullPath(assemblyPath);
			Assembly assembly = Assembly.LoadFile(fullPath);
			Type[] types = assembly.GetTypes();
			foreach (Type type in types)
			{
				if (!type.IsClass)
				{
					continue;
				}
				Attribute[] customAttributes = Attribute.GetCustomAttributes(type);
				if (customAttributes.Length <= 0)
				{
					continue;
				}
				Attribute[] array = customAttributes;
				foreach (Attribute attribute in array)
				{
					if (attribute is SupportedResourceNameAttribute supportedResourceNameAttribute)
					{
						list.Add(supportedResourceNameAttribute.Support);
					}
				}
			}
		}
		catch
		{
		}
		return list;
	}

	private List<string> getSpecificAssemblyList<T>()
	{
		List<string> list = new List<string>();
		string currentDirectory = Directory.GetCurrentDirectory();
		string[] files = Directory.GetFiles(currentDirectory, "*.dll");
		string[] array = files;
		foreach (string path in array)
		{
			try
			{
				string fileName = Path.GetFileName(path);
				if (!fileName.StartsWith("QFDT") && !fileName.StartsWith("qfdt"))
				{
					continue;
				}
				Assembly assembly = Assembly.LoadFile(path);
				Type[] types = assembly.GetTypes();
				foreach (Type type in types)
				{
					if (type.IsClass && type.GetInterfaces().Contains(typeof(T)))
					{
						list.Add(Path.GetFileName(path));
						break;
					}
				}
			}
			catch
			{
			}
		}
		return list;
	}

	private void InitEquipComponentGroups<T>(object driverTypeComboBox, object dllComboBox, object resNameComboBox, object resGpibTextBox, object resVisaTextBox, BasicEquipConfig EquipCfg)
	{
		try
		{
			List<string> specificAssemblyList = getSpecificAssemblyList<T>();
			System.Windows.Controls.ComboBox obj = dllComboBox as System.Windows.Controls.ComboBox;
			InitSpecialComboBox(obj, specificAssemblyList, EquipCfg.RelativePath);
			List<string> supportedList = getSupportedList(EquipCfg.RelativePath);
			System.Windows.Controls.ComboBox obj2 = resNameComboBox as System.Windows.Controls.ComboBox;
			InitSpecialComboBox(obj2, supportedList, EquipCfg.TE_type);
			System.Windows.Controls.ComboBox comboBox = driverTypeComboBox as System.Windows.Controls.ComboBox;
			comboBox.SelectedItem = ((!(EquipCfg.driverType == TEDriverType.gpib_32.ToString())) ? TEDriverType.visa32 : TEDriverType.gpib_32);
			System.Windows.Controls.TextBox textBox = resGpibTextBox as System.Windows.Controls.TextBox;
			textBox.Text = EquipCfg.gpib;
			System.Windows.Controls.TextBox textBox2 = resVisaTextBox as System.Windows.Controls.TextBox;
			textBox2.Text = EquipCfg.visa32_desc;
		}
		catch
		{
		}
	}

	private void SetCustomizedVsibility(StackPanel spForGpib32, StackPanel spForVisa32, TEDriverType dtype)
	{
		switch (dtype)
		{
		case TEDriverType.gpib_32:
			spForGpib32.Visibility = Visibility.Visible;
			spForVisa32.Visibility = Visibility.Collapsed;
			break;
		case TEDriverType.visa32:
			spForGpib32.Visibility = Visibility.Collapsed;
			spForVisa32.Visibility = Visibility.Visible;
			break;
		}
	}

	private void PSDriverType_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		TEDriverType dtype = TEDriverType.gpib_32;
		if (cbxPSDriver.SelectedItem != null)
		{
			dtype = (TEDriverType)cbxPSDriver.SelectedItem;
		}
		SetCustomizedVsibility(spPowerSupplyGpibSetting, spPowerSupplyVISASetting, dtype);
	}

	private void SpecAnDriverType_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		TEDriverType dtype = TEDriverType.gpib_32;
		if (cbxSpecAnDriver.SelectedItem != null)
		{
			dtype = (TEDriverType)cbxSpecAnDriver.SelectedItem;
		}
		SetCustomizedVsibility(spSpecAnGpibSetting, spSpecAnVISASetting, dtype);
	}

	private void SiggenDriverType_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		TEDriverType dtype = TEDriverType.gpib_32;
		if (cbxSiggenDriver.SelectedItem != null)
		{
			dtype = (TEDriverType)cbxSiggenDriver.SelectedItem;
		}
		SetCustomizedVsibility(spSiggenGpibSetting, spSiggenVISASetting, dtype);
	}

	private void EquipDll_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		if (!(sender is System.Windows.Controls.ComboBox { SelectedValue: not null } comboBox))
		{
			return;
		}
		List<string> supportedList = getSupportedList(comboBox.SelectedValue.ToString());
		System.Windows.Controls.ComboBox comboBox2 = null;
		if (comboBox.Name == "ps_dll_combo")
		{
			comboBox2 = ps_resource_name;
		}
		else if (comboBox.Name == "specan_dll_combo")
		{
			comboBox2 = specan_resource_name;
		}
		else if (comboBox.Name == "siggen_dll_combo")
		{
			comboBox2 = siggen_resource_name;
		}
		if (comboBox2 != null)
		{
			string lastResName = null;
			if (comboBox2.SelectedValue != null)
			{
				lastResName = comboBox2.SelectedValue.ToString();
			}
			comboBox2.Items.Clear();
			InitSpecialComboBox(comboBox2, supportedList, null);
			if (lastResName != null && supportedList.Exists((string r) => r == lastResName))
			{
				comboBox2.SelectedValue = lastResName;
			}
		}
	}
}
