using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Xml.Serialization;
using QC.QMSLPhone;
using QFDT_XML;
using QSC_Params_File_Helper;
using Qualcomm_ModemRFA;

namespace QFDT_Components;

public partial class RFPathAndRadioConfiguration : UserControl, IComponentConnector
{
	public delegate void SendBandSelectedMessage(TechAndBandCombine selBand);

	public delegate void SendDebugMessage(MessageLevel level, string message);

	public SendDebugMessage DebugMessageCB;

	public SendBandSelectedMessage BandSelMessageCB;

	public DebugRFType m_RFType;

	public TechAndBandCombine m_curBand;

	public availablePaths m_curAvailPaths;

	public availablePathType m_curPath;

	public Phone phone;

	public static Platform m_platform;

	private List<StructFtmUnifiedTxRxPathInfoVersion0> pathInfoItemList = new List<StructFtmUnifiedTxRxPathInfoVersion0>();

	private structFtmUnifiedTxRxPathInfoResponse calPathInfo;

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

	public RFPathAndRadioConfiguration()
	{
		InitializeComponent();
		SetLanguageDictionary();
		InitUI();
		m_curPath = null;
	}

	public void InitUI()
	{
		comboBxQSCBand.Items.Clear();
		lbAvailRFPath.Visibility = Visibility.Hidden;
	}

	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 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 SetPlatform(Platform platform)
	{
		m_platform = platform;
		availablePathType.isAT = m_platform == Platform.AT;
		UpdateUIViaPlatform(m_platform);
	}

	private void UpdateUIViaPlatform(Platform platform)
	{
		if (platform == Platform.AT)
		{
			lbAvailRFPath.Visibility = Visibility.Visible;
			lbx_Available_RF_Path.Visibility = Visibility.Visible;
			gridQueryResult.Visibility = Visibility.Hidden;
			pnlFilter.Visibility = Visibility.Hidden;
		}
		else
		{
			lbAvailRFPath.Visibility = Visibility.Hidden;
			lbx_Available_RF_Path.Visibility = Visibility.Hidden;
			gridQueryResult.Visibility = Visibility.Visible;
			pnlFilter.Visibility = Visibility.Visible;
		}
	}

	public bool UpdateComboBoxBandsViaXML(string calQSCXML, ref string strLog)
	{
		QSC_Param_Query qSC_Param_Query = new QSC_Param_Query();
		string exceptionMessage = "";
		string bandStr = "";
		List<Tuple<string, string>> bands = new List<Tuple<string, string>>();
		List<string> list = new List<string>();
		list.Add("LTE");
		list.Add("CDMA");
		list.Add("WCDMA");
		list.Add("TDSCDMA");
		list.Add("NR5GSUB6");
		List<string> list2 = list;
		comboBxQSCBand.Items.Clear();
		if (qSC_Param_Query.LoadQSCParamsFile(calQSCXML, ref exceptionMessage))
		{
			for (int i = 0; i < list2.Count; i++)
			{
				if ((m_RFType == DebugRFType.TX) ? qSC_Param_Query.Get_Bands_From_Unconnected_Nodes(list2[i], ref bands, ref bandStr) : qSC_Param_Query.Get_Bands_From_Connected_Nodes(list2[i], ref bands, ref bandStr))
				{
					for (int j = 0; j < bands.Count; j++)
					{
						comboBxQSCBand.Items.Add(new TechAndBandCombine(list2[i], bands[j].Item1, bands[j].Item2));
					}
				}
			}
			comboBxQSCBand.Items.Add(new TechAndBandCombine("GSM", "0", "0"));
			comboBxQSCBand.Items.Add(new TechAndBandCombine("GSM", "1", "0"));
			comboBxQSCBand.Items.Add(new TechAndBandCombine("GSM", "2", "0"));
			comboBxQSCBand.Items.Add(new TechAndBandCombine("GSM", "3", "0"));
			strLog = "Load QSC xml file success.";
			return true;
		}
		int num = exceptionMessage.IndexOf("\r\n");
		if (num > -1)
		{
			exceptionMessage = exceptionMessage.Substring(0, num);
		}
		strLog = "Load QSC xml file fail: " + exceptionMessage;
		return false;
	}

	public bool UpdateUIviaXML(string calQSCXML, ref string strLog)
	{
		lbx_Available_RF_Path.Items.Clear();
		return UpdateComboBoxBandsViaXML(calQSCXML, ref strLog);
	}

	private bool QueryRFPathFromPhone()
	{
		if (phone != null)
		{
			try
			{
				if (m_platform == Platform.AT)
				{
					Phone.structRFPathInformationRequest req = new Phone.structRFPathInformationRequest();
					req.technology = TechAndBandCombine.techMap[m_curBand.tech];
					req.band = ushort.Parse(m_curBand.band);
					req.subBand = byte.Parse(m_curBand.subband);
					req.version = 1;
					Phone.structRFPathInformationResponse_NoExpanded rsp = default(Phone.structRFPathInformationResponse_NoExpanded);
					phone.FTM_GET_RF_PATH_INFORMATION(ref req, ref rsp);
					m_curAvailPaths = new availablePaths();
					m_curAvailPaths.GetAvailablePathViaPhoneRsp(rsp);
					if (m_curAvailPaths.availPaths.Count > 0)
					{
						m_curPath = m_curAvailPaths.availPaths[0];
					}
				}
				else
				{
					Phone.structFTM_RF_TEST_PROPERTY_DATA_BULK req2 = default(Phone.structFTM_RF_TEST_PROPERTY_DATA_BULK);
					req2.num_properties = 5u;
					req2.propertyData = new Phone.structFtmRfTestPropertyDataType[5];
					req2.propertyData[0].type = 0u;
					req2.propertyData[0].value = TechAndBandCombine.techMap[m_curBand.tech];
					req2.propertyData[1].type = 2u;
					req2.propertyData[1].value = ulong.Parse(m_curBand.band);
					req2.propertyData[2].type = 3u;
					req2.propertyData[2].value = ulong.Parse(m_curBand.subband);
					req2.propertyData[3].type = 1u;
					req2.propertyData[3].value = 65535uL;
					req2.propertyData[4].type = 13u;
					req2.propertyData[4].value = 65535uL;
					Phone.structFtmUnifiedTxRxPathInfoResponse rsp2 = default(Phone.structFtmUnifiedTxRxPathInfoResponse);
					phone.FTM_GET_UNIFIED_RF_PATH_INFORMATION(ref req2, ref rsp2);
					DebugMessageCB(MessageLevel.SUCCESS, "TECH TOTAL BANDS: " + rsp2.numberofbands);
					Phone.structFtmUnifiedTxRxPathInfoBandData[] bandData = rsp2.bandData;
					for (int i = 0; i < bandData.Length; i++)
					{
						Phone.structFtmUnifiedTxRxPathInfoBandData structFtmUnifiedTxRxPathInfoBandData = bandData[i];
						DebugMessageCB(MessageLevel.SUCCESS, "BAND " + structFtmUnifiedTxRxPathInfoBandData.band);
					}
					XmlSerializer xmlSerializer = new XmlSerializer(typeof(Phone.structFtmUnifiedTxRxPathInfoResponse));
					using (StreamWriter streamWriter = new StreamWriter("C:\\qualcomm\\QDART\\QFDT\\UnifiedPathInfo.xml"))
					{
						xmlSerializer.Serialize(streamWriter, rsp2);
						streamWriter.Close();
					}
					using (FileStream fileStream = new FileStream("C:\\qualcomm\\QDART\\QFDT\\UnifiedPathInfo.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
					{
						XmlSerializer xmlSerializer2 = new XmlSerializer(typeof(structFtmUnifiedTxRxPathInfoResponse));
						calPathInfo = (structFtmUnifiedTxRxPathInfoResponse)xmlSerializer2.Deserialize(fileStream);
						pathInfoItemList = calPathInfo.bandData[0].version0Data.ToList();
						fileStream.Close();
					}
					gridQueryResult.ItemsSource = null;
					gridQueryResult.ItemsSource = pathInfoItemList;
					m_curAvailPaths = new availablePaths();
					m_curAvailPaths.GetAvailablePathViaPhoneRsp(rsp2);
					if (m_curAvailPaths.availPaths.Count > 0)
					{
						m_curPath = m_curAvailPaths.availPaths[0];
					}
				}
				return true;
			}
			catch (PhoneException ex)
			{
				DebugMessageCB(MessageLevel.EXCEPTION, "PhoneException " + ex.Message);
				m_curPath = null;
				return false;
			}
			catch (Exception ex2)
			{
				DebugMessageCB(MessageLevel.EXCEPTION, "Unknown Exception " + ex2.Message);
				m_curPath = null;
				return false;
			}
		}
		DebugMessageCB(MessageLevel.EXCEPTION, "Invalid phone handle, can't get RF path from phone");
		m_curPath = null;
		return false;
	}

	private bool GetRFPath()
	{
		if (comboBxQSCBand.SelectedItem != null)
		{
			m_curBand = (TechAndBandCombine)comboBxQSCBand.SelectedItem;
			lbx_Available_RF_Path.Items.Clear();
			m_curPath = null;
			if (QueryRFPathFromPhone())
			{
				if (m_platform == Platform.AT && m_curAvailPaths.availPaths != null && m_curAvailPaths.availPaths.Count > 0)
				{
					for (int i = 0; i < m_curAvailPaths.availPaths.Count; i++)
					{
						lbx_Available_RF_Path.Items.Add(m_curAvailPaths.availPaths[i]);
					}
				}
				return true;
			}
			MessageBox.Show("Please connect phone to get path info for current band");
			comboBxQSCBand.SelectedItem = null;
			return false;
		}
		return false;
	}

	private void Path_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		if (lbx_Available_RF_Path.SelectedItem != null)
		{
			m_curPath = (availablePathType)lbx_Available_RF_Path.SelectedItem;
			BandSelMessageCB((TechAndBandCombine)comboBxQSCBand.SelectedItem);
		}
		else
		{
			m_curPath = null;
		}
	}

	private void TechBand_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		if (GetRFPath())
		{
			if (lbx_Available_RF_Path.Items.Count > 0)
			{
				lbx_Available_RF_Path.SelectedIndex = 0;
			}
			if (comboBxQSCBand.SelectedItem != null)
			{
				BandSelMessageCB((TechAndBandCombine)comboBxQSCBand.SelectedItem);
			}
		}
	}

	private void gridQueryResult_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		if (gridQueryResult.SelectedItem != null)
		{
			int index = int.Parse(((StructFtmUnifiedTxRxPathInfoVersion0)gridQueryResult.SelectedItem).pathID);
			m_curPath = m_curAvailPaths.availPaths[index];
			BandSelMessageCB((TechAndBandCombine)comboBxQSCBand.SelectedItem);
		}
	}

	private void FilterPath_SelectionChanged(object sender, EventArgs e)
	{
		if (calPathInfo != null)
		{
			gridQueryResult.ItemsSource = calPathInfo.bandData[0].version0Data.Where((StructFtmUnifiedTxRxPathInfoVersion0 res) => (res.CAL_ACTION == cbCalActionType.Text || cbCalActionType.SelectedIndex == -1) && (res.antenna_config_state == cbAntConfigState.Text || cbAntConfigState.SelectedIndex == -1) && (res.antenna_number == cbAntNumber.Text || cbAntNumber.SelectedIndex == -1));
		}
	}

	private void btnUnFilterQueryResults_Click(object sender, RoutedEventArgs e)
	{
		if (calPathInfo != null)
		{
			gridQueryResult.ItemsSource = null;
			gridQueryResult.ItemsSource = calPathInfo.bandData[0].version0Data;
			cbCalActionType.SelectedIndex = -1;
			cbAntNumber.SelectedIndex = -1;
			cbAntConfigState.SelectedIndex = -1;
		}
	}

	private void genRadioCfgReqOnSinglePath(ref List<FTM_RF_Debug_Property_Date_Type> ps, RFPathStruct path, byte pathType, string band, int subbandId, uint Channel, int wfm, int BW, int NumOfRB, int StartRB)
	{
		DebugMessageCB(MessageLevel.SUCCESS, "PATH: " + path);
		PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["RFM Device"], path.RFM_Device);
		PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Signal Path"], path.Sig_Path);
		PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Antenna Path"], path.Ant_Path);
		PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["RFM Path Type"], pathType);
		PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Band"], long.Parse(band));
		PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Subband"], subbandId);
		PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Channel"], Channel);
		if (pathType == PropertyValueMap.Radio_Cfg_Path_Value_Map["Tx"])
		{
			PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Tx Waveform Type"], wfm);
		}
		if (m_curBand.tech == "LTE" || m_curBand.tech == "NR5GSUB6")
		{
			PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Bandwidth"], BW);
		}
		if (pathType == PropertyValueMap.Radio_Cfg_Path_Value_Map["Tx"] && (m_curBand.tech == "LTE" || m_curBand.tech == "NR5GSUB6"))
		{
			PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Number Of RBs"], NumOfRB);
			PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Start RB Index"], StartRB);
			if (m_platform == Platform.HE && m_curBand.tech == "LTE")
			{
				PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Mod_Type"], 0L);
				PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Change Modulation"], 0L);
			}
		}
		if (m_platform == Platform.HE)
		{
			PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["PLL_ID"], path.PLL_ID);
		}
	}

	private FTM_RF_Debug_Property_Struct GenRadioConfigReqStruct(availablePathType path, uint ULChannel, int wfm, int BW, int NumOfRB, int StartRB, bool IsTearDown)
	{
		FTM_RF_Debug_Property_Struct result = default(FTM_RF_Debug_Property_Struct);
		List<FTM_RF_Debug_Property_Date_Type> ps = new List<FTM_RF_Debug_Property_Date_Type>();
		try
		{
			PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Is Tear Down"], IsTearDown ? 1 : 0);
			if (!IsTearDown)
			{
				PropertyValueMap.AddOnePropertyToList(ref ps, PropertyValueMap.Radio_Cfg_Property_Type_Map["Radio Setup Type"], PropertyValueMap.Radio_Cfg_Setup_Type_Map["TECH_BAND_RFMPATH_CHAN"]);
				ushort iBand = TechAndBandCombine.ChangeToBandHelperBandClass(m_curBand.tech, m_curBand.band);
				uint channel = phone.Band_Helper_CalculateDLChannel(iBand, ULChannel);
				genRadioCfgReqOnSinglePath(ref ps, path.PRxPath, PropertyValueMap.Radio_Cfg_Path_Value_Map["PRx"], m_curBand.band, int.Parse(m_curBand.subband), channel, wfm, BW, NumOfRB, StartRB);
				if (m_curBand.tech == "NR5GSUB6")
				{
					genRadioCfgReqOnSinglePath(ref ps, path.DRxPath, PropertyValueMap.Radio_Cfg_Path_Value_Map_SUB6["Rx"], m_curBand.band, int.Parse(m_curBand.subband), channel, wfm, BW, NumOfRB, StartRB);
				}
				else if (path.bValidDRx || m_platform == Platform.HE)
				{
					genRadioCfgReqOnSinglePath(ref ps, path.DRxPath, PropertyValueMap.Radio_Cfg_Path_Value_Map["DRx"], m_curBand.band, int.Parse(m_curBand.subband), channel, wfm, BW, NumOfRB, StartRB);
				}
				genRadioCfgReqOnSinglePath(ref ps, path.TxPath, PropertyValueMap.Radio_Cfg_Path_Value_Map["Tx"], m_curBand.band, int.Parse(m_curBand.subband), ULChannel, wfm, BW, NumOfRB, StartRB);
			}
			result.num_properties = (uint)ps.Count;
			result.properties = new FTM_RF_Debug_Property_Date_Type[ps.Count];
			for (int i = 0; i < ps.Count; i++)
			{
				ref FTM_RF_Debug_Property_Date_Type reference = ref result.properties[i];
				reference = ps[i];
			}
		}
		catch (Exception ex)
		{
			DebugMessageCB(MessageLevel.EXCEPTION, "Unknown Exception " + ex.Message);
		}
		return result;
	}

	public bool SetupRadioConfiguration(uint ULChannel, int wfm, int BW, int NumOfRB, int StartRB, bool IsTearDown)
	{
		FTM_RF_Debug_Property_Struct req_struct = GenRadioConfigReqStruct(m_curPath, ULChannel, wfm, BW, NumOfRB, StartRB, IsTearDown);
		FTM_RF_Debug_Property_Struct rsp_struct = default(FTM_RF_Debug_Property_Struct);
		uint error_code = 0u;
		uint specific_err_code = 0u;
		if (phone != null)
		{
			try
			{
				DebugMessageCB(MessageLevel.SUCCESS, m_curPath.ToString());
				phone.FTM_RF_DEBUG_CMD_RADIO_CONFIGURE(PropertyValueMap.FTM_RF_Debug_Tech_Map[m_curBand.tech], ref req_struct, ref rsp_struct, ref error_code, ref specific_err_code);
				if (error_code == 0 && specific_err_code == 0)
				{
					DebugMessageCB(MessageLevel.SUCCESS, "FTM_RF_DEBUG_CMD_RADIO_CONFIGURE " + (IsTearDown ? "Tear Down " : "") + "success");
					return true;
				}
				DebugMessageCB(MessageLevel.FAIL, "Set RadioConfig fail, return error code != 0");
				return false;
			}
			catch (PhoneException ex)
			{
				DebugMessageCB(MessageLevel.EXCEPTION, "PhoneException " + ex.Message);
				return false;
			}
			catch (Exception ex2)
			{
				DebugMessageCB(MessageLevel.EXCEPTION, "Unknown Exception " + ex2.Message);
				return false;
			}
		}
		MessageBox.Show("Invalid phone handle");
		return false;
	}
}
