using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using DebugToolInstrumentInterface;
using QC.QMSLPhone;
using Qualcomm_ModemRFA;

namespace QFDT_Components;

public partial class FTM_RF_Tx : UserControl, IComponentConnector
{
	public delegate void SendDebugMessage(MessageLevel level, string message);

	public SendDebugMessage DebugMessageCB;

	public string TableName = "TestingTable";

	public Phone phone;

	public double Frequency;

	public ISpectrumAnalyzer pSA;

	private List<TxPowerAction> List;

	private TxPowerAction currentPowerAction;

	public void Register_DebugMessageCB(SendDebugMessage me)
	{
		DebugMessageCB = me;
	}

	public FTM_RF_Tx()
	{
		InitializeComponent();
		SetLanguageDictionary();
	}

	private void SetLanguageDictionary()
	{
		ResourceDictionary resourceDictionary = new ResourceDictionary();
		string text = Thread.CurrentThread.CurrentCulture.ToString();
		try
		{
			resourceDictionary.Source = new Uri(Thread.GetDomain().BaseDirectory + "..\\Resources\\UI_" + text + ".xaml", UriKind.Absolute);
		}
		catch
		{
		}
		base.Resources.MergedDictionaries.Add(resourceDictionary);
	}

	public void SetUpUIviaXML(string calV4XML)
	{
		CalV4Parser calV4Parser = new CalV4Parser();
		calV4Parser.ParseCalV4File(calV4XML);
		List<TxPowerAction> maxTxPowerActionFromAllTechnologies = calV4Parser.GetMaxTxPowerActionFromAllTechnologies();
		SetUpUI(maxTxPowerActionFromAllTechnologies);
	}

	private void ClearAllTextBoxes()
	{
		Channel.Text = "";
		ChanInMHz.Text = "";
		RGI.Text = "";
		Bias.Text = "";
		State.Text = "";
		Min_Pwr.Text = "";
		Max_Pwr.Text = "";
		PLLoss.Text = "";
		OutputPower.Text = "";
		SetUIComponentAttr(OutputPower, SetAttribute.BGColor, UserDefinedColorType.DEFAULT);
	}

	public void SetUpUI(List<TxPowerAction> TxPowerActionList)
	{
		ClearAllTextBoxes();
		comboSecneario.Items.Clear();
		if (TxPowerActionList != null)
		{
			for (int i = 0; i < TxPowerActionList.Count; i++)
			{
				comboSecneario.Items.Add(TxPowerActionList[i].Description);
			}
		}
		List = TxPowerActionList;
		LoadExtraSettings();
	}

	private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		ComboBox comboBox = (ComboBox)sender;
		if (comboBox.Items.Count > 0)
		{
			Bias.Text = List[comboSecneario.SelectedIndex].Bias.ToString();
			RGI.Text = List[comboSecneario.SelectedIndex].RGI.ToString();
			State.Text = List[comboSecneario.SelectedIndex].PA_State.ToString();
			Channel.Text = List[comboSecneario.SelectedIndex].Ref_Chan.ToString();
			currentPowerAction = List[comboSecneario.SelectedIndex];
			CalV4Parser.ModeIDToQMSLBandHelperBandClass(List[comboSecneario.SelectedIndex].RFmode_ID);
			if (phone != null)
			{
				double num = (Frequency = phone.Band_Helper_CalculateULFrequency((ushort)CalV4Parser.ModeIDToQMSLBandHelperBandClass(List[comboSecneario.SelectedIndex].RFmode_ID), (uint)List[comboSecneario.SelectedIndex].Ref_Chan));
				ChanInMHz.Text = num + "MHz";
				PLLoss.Text = "0";
			}
			Min_Pwr.Text = ((List[comboSecneario.SelectedIndex].LowerLim != null) ? List[comboSecneario.SelectedIndex].LowerLim.ToString() : List[comboSecneario.SelectedIndex].Min_Start_Pwr.ToString());
			Max_Pwr.Text = ((List[comboSecneario.SelectedIndex].UpperLim != null) ? List[comboSecneario.SelectedIndex].UpperLim.ToString() : List[comboSecneario.SelectedIndex].Max_Expected_Pwr.ToString());
		}
	}

	private void TxOn_Click(object sender, RoutedEventArgs e)
	{
		if (comboSecneario.SelectedIndex == -1)
		{
			DebugMessageCB(MessageLevel.FAIL, base.Resources["SelectTx"].ToString());
		}
		else
		{
			if (phone == null)
			{
				return;
			}
			try
			{
				AccessComponentInThreadHelper.SetText(this, OutputPower, SetAttribute.Text, "");
				phone.FTM_SET_CAL_MODE(1);
				phone.FTM_SET_MODE_ID((FTM_Mode_Id_Enum)currentPowerAction.modeID);
				phone.FTM_SET_MODE((FTM_RF_Mode_Enum)currentPowerAction.RFmode_ID);
				if (CalV4Parser.IsTech(CalV4Parser.Tech.LTE, (CalV4Parser.FTM_PHONE_MODE_ENUM)currentPowerAction.RFmode_ID) && currentPowerAction.LTE_waveform != null)
				{
					phone.FTM_LTE_SET_TX_BANDWIDTH((byte)currentPowerAction.LTE_waveform.Tx_BW);
					phone.FTM_LTE_SET_RX_BANDWIDTH((byte)currentPowerAction.LTE_waveform.Rx_BW);
				}
				ushort num = Convert.ToUInt16(Channel.Text);
				Convert.ToUInt16(State.Text);
				phone.FTM_SET_CHAN(num);
				if (CalV4Parser.IsTech(CalV4Parser.Tech.LTE, (CalV4Parser.FTM_PHONE_MODE_ENUM)currentPowerAction.RFmode_ID) && currentPowerAction.LTE_waveform != null)
				{
					phone.FTM_LTE_SET_TX_WAVEFORM(1, (byte)currentPowerAction.LTE_waveform.Number_Of_RBs, 0, (byte)currentPowerAction.LTE_waveform.Start_RB);
				}
				byte eDevice = (byte)currentPowerAction.Device;
				byte eXPT_type = 0;
				byte eIQ_Override_type = 1;
				uint iIQ_gain = Convert.ToUInt32(currentPowerAction.IQGain);
				byte eEnvSc_Override_type = 1;
				uint iEnvScale = Convert.ToUInt32(currentPowerAction.EnvGain);
				ushort num2 = Convert.ToUInt16(RGI.Text);
				ushort iPA_bias = Convert.ToUInt16(Bias.Text);
				byte b = Convert.ToByte(State.Text);
				ushort iPA_curr = Convert.ToUInt16(currentPowerAction.PA_Quiescent_Current);
				byte eDelay_Override_type = 2;
				uint iDelay_us = 0u;
				phone.FTM_SET_TX_ON();
				phone.FTM_XPT_TXAGC_OVERRIDE(eDevice, eXPT_type, eIQ_Override_type, iIQ_gain, eEnvSc_Override_type, iEnvScale, num2, iPA_bias, b, iPA_curr, eDelay_Override_type, iDelay_us);
				if (pSA != null)
				{
					double centerFrequency = phone.Band_Helper_CalculateULFrequency((ushort)CalV4Parser.ModeIDToQMSLBandHelperBandClass(List[comboSecneario.SelectedIndex].RFmode_ID), Convert.ToUInt16(Channel.Text));
					if (CalV4Parser.IsTech(CalV4Parser.Tech.LTE, (CalV4Parser.FTM_PHONE_MODE_ENUM)currentPowerAction.RFmode_ID))
					{
						pSA.SetupMeasurement(Technology.LTE);
						pSA.SetSpan(10.0);
					}
					if (CalV4Parser.IsTech(CalV4Parser.Tech.WCDMA, (CalV4Parser.FTM_PHONE_MODE_ENUM)currentPowerAction.RFmode_ID))
					{
						pSA.SetupMeasurement(Technology.WCDMA);
						pSA.SetSpan(5.0);
					}
					if (CalV4Parser.IsTech(CalV4Parser.Tech.TDSCDMA, (CalV4Parser.FTM_PHONE_MODE_ENUM)currentPowerAction.RFmode_ID))
					{
						pSA.SetupMeasurement(Technology.TDSCDMA);
						pSA.SetSpan(5.0);
					}
					if (CalV4Parser.IsTech(CalV4Parser.Tech.CDMA, (CalV4Parser.FTM_PHONE_MODE_ENUM)currentPowerAction.RFmode_ID))
					{
						pSA.SetupMeasurement(Technology.CDMA);
						pSA.SetSpan(2.0);
					}
					AddEntry();
					pSA.SetCenterFrequency(centerFrequency);
					pSA.SetReferenceLevel(currentPowerAction.Max_Expected_Pwr);
					AccessComponentInThreadHelper.SetText(this, OutputPower, SetAttribute.Text, pSA.GetPower());
					JudgePwrLevel();
				}
				string message = base.Resources["SetTXonRF"].ToString() + ":" + ((FTM_RF_Mode_Enum)currentPowerAction.RFmode_ID).ToString() + " Channel:" + num + " PA State:" + b + " RGI:" + num2 + " SUCCESS !";
				DebugMessageCB(MessageLevel.SUCCESS, message);
			}
			catch (PhoneException ex)
			{
				DebugMessageCB(MessageLevel.EXCEPTION, "PhoneException " + ex.Message);
			}
			catch (Exception ex2)
			{
				DebugMessageCB(MessageLevel.EXCEPTION, "Unknown Exception " + ex2.Message);
				_ = ex2.Message == "Tech not supported";
			}
		}
	}

	public void SetUIComponentAttr<T>(T component, SetAttribute attr, UserDefinedColorType value)
	{
		if (!(component is TextBox))
		{
			return;
		}
		TextBox textBox = component as TextBox;
		if (attr == SetAttribute.BGColor)
		{
			switch (value)
			{
			case UserDefinedColorType.RED:
				textBox.Background = new SolidColorBrush(Color.FromArgb(byte.MaxValue, byte.MaxValue, 0, 0));
				break;
			case UserDefinedColorType.GREEN:
				textBox.Background = new SolidColorBrush(Color.FromArgb(byte.MaxValue, 0, byte.MaxValue, 0));
				break;
			case UserDefinedColorType.DEFAULT:
				textBox.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
				break;
			}
		}
	}

	private void JudgePwrLevel()
	{
		double? num = null;
		double? num2 = null;
		double? num3 = null;
		if (double.TryParse(Min_Pwr.Text, out var result))
		{
			num = result;
		}
		if (double.TryParse(Max_Pwr.Text, out result))
		{
			num2 = result;
		}
		if (double.TryParse(OutputPower.Text, out result))
		{
			num3 = result;
		}
		if (!num3.HasValue)
		{
			DebugMessageCB(MessageLevel.EXCEPTION, "invalid Power Value!");
			SetUIComponentAttr(OutputPower, SetAttribute.BGColor, UserDefinedColorType.RED);
		}
		else if (num.HasValue || num2.HasValue)
		{
			bool flag = false;
			if (num.HasValue && num3 < num)
			{
				flag = true;
				DebugMessageCB(MessageLevel.FAIL, "The Tx power is below the lower limit");
				SetUIComponentAttr(OutputPower, SetAttribute.BGColor, UserDefinedColorType.RED);
			}
			if (num2.HasValue && num3 > num2)
			{
				flag = true;
				DebugMessageCB(MessageLevel.FAIL, "The Tx power is above the upper limit");
				SetUIComponentAttr(OutputPower, SetAttribute.BGColor, UserDefinedColorType.RED);
			}
			if (!flag)
			{
				SetUIComponentAttr(OutputPower, SetAttribute.BGColor, UserDefinedColorType.GREEN);
			}
		}
		else
		{
			SetUIComponentAttr(OutputPower, SetAttribute.BGColor, UserDefinedColorType.DEFAULT);
		}
	}

	private void TxOff_Click(object sender, RoutedEventArgs e)
	{
		if (comboSecneario.SelectedIndex == -1)
		{
			DebugMessageCB(MessageLevel.FAIL, base.Resources["SelectTx"].ToString());
		}
		else if (phone != null)
		{
			try
			{
				phone.FTM_SET_CAL_MODE(1);
				phone.FTM_SET_MODE_ID((FTM_Mode_Id_Enum)currentPowerAction.modeID);
				phone.FTM_SET_MODE((FTM_RF_Mode_Enum)currentPowerAction.RFmode_ID);
				ushort num = Convert.ToUInt16(Channel.Text);
				phone.FTM_SET_CHAN(num);
				phone.FTM_SET_TX_OFF();
				string message = base.Resources["SetTXoffRF"].ToString() + ":" + ((FTM_RF_Mode_Enum)currentPowerAction.RFmode_ID).ToString() + " Channel:" + num + " SUCCESS !";
				DebugMessageCB(MessageLevel.SUCCESS, message);
			}
			catch (PhoneException ex)
			{
				DebugMessageCB(MessageLevel.EXCEPTION, "PhoneException " + ex.Message);
			}
		}
	}

	private void AddEntry()
	{
		if (pSA == null)
		{
			return;
		}
		if (string.IsNullOrWhiteSpace(PLLoss.Text))
		{
			DebugMessageCB(MessageLevel.FAIL, base.Resources["PathLossCorrection"].ToString());
			return;
		}
		try
		{
			bool flag = false;
			double.TryParse(PLLoss.Text, out var result);
			if (pSA.SetPathLoss(Frequency, result, TableName) && result != 0.0)
			{
				DebugMessageCB(MessageLevel.SUCCESS, base.Resources["PathLossApplied"].ToString());
				pSA.SetPathLoss(TableName, "1", "1");
			}
		}
		catch (Exception ex)
		{
			DebugMessageCB(MessageLevel.EXCEPTION, "Unknown exception: " + ex.Message);
		}
	}

	private void ChannelValueChanged(object sender, TextChangedEventArgs e)
	{
		if (Channel.Text.Length > 0 && phone != null)
		{
			double num = phone.Band_Helper_CalculateULFrequency((ushort)CalV4Parser.ModeIDToQMSLBandHelperBandClass(List[comboSecneario.SelectedIndex].RFmode_ID), Convert.ToUInt16(Channel.Text));
			ChanInMHz.Text = num + " MHz";
		}
	}

	public void SetLanguage(string culture)
	{
		ResourceDictionary resourceDictionary = new ResourceDictionary();
		try
		{
			resourceDictionary.Source = new Uri(Thread.GetDomain().BaseDirectory + "\\Resources\\UI_" + culture + ".xaml", UriKind.Absolute);
		}
		catch
		{
			resourceDictionary.Source = new Uri(Thread.GetDomain().BaseDirectory + "..\\Resources\\UI_en-US.xaml", UriKind.Absolute);
		}
		base.Resources.MergedDictionaries.Clear();
		base.Resources.MergedDictionaries.Add(resourceDictionary);
	}

	public void LoadExtraSettings()
	{
		if (pSA != null)
		{
			if (pSA.IsCalTableSupported())
			{
				PLLoss.Visibility = Visibility.Visible;
				Loss_Label.Visibility = Visibility.Visible;
			}
			else
			{
				PLLoss.Visibility = Visibility.Collapsed;
				Loss_Label.Visibility = Visibility.Collapsed;
			}
			if (pSA.IsGetPowerSupported())
			{
				Power_dBM.Visibility = Visibility.Visible;
				OutputPower.Visibility = Visibility.Visible;
			}
			else
			{
				Power_dBM.Visibility = Visibility.Collapsed;
				OutputPower.Visibility = Visibility.Collapsed;
			}
		}
	}
}
