using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Xml;
using System.Xml.Serialization;
using QC.QMSLPhone;
using QRCT_modem_RF_Debug_tool;
using QSPR3xttParse;
using Qualcomm_ModemRFA;

namespace QFDT_Components;

public partial class PCF_Wizard : UserControl, IComponentConnector
{
	public enum EditModeEnum
	{
		New,
		Edit
	}

	public delegate void NewProductCreated();

	public const int MAX_RESOURCES = 5;

	private string productConfigurationFolder;

	private EditModeEnum editMode;

	public Phone phone;

	public NewProductCreated created;

	private PCF m_currentPCF;

	public EditModeEnum EditMode
	{
		get
		{
			return editMode;
		}
		set
		{
			editMode = value;
		}
	}

	public string ProductConfigurationFolder
	{
		set
		{
			productConfigurationFolder = value;
		}
	}

	public PCF_Wizard()
	{
		InitializeComponent();
		editMode = EditModeEnum.New;
	}

	public void AddNewProductCreated(NewProductCreated me)
	{
		created = me;
	}

	private bool updateWWANCalXMLInfo(QSPR3XTT xttParser, FileInfo xttFileInfo, string ProductProductPath, string ProductName, string calVersion, ref string FullPath)
	{
		string text = "";
		FullPath = "";
		if (calVersion == Cal_Version.V4.ToString())
		{
			if (!IsXTTCalV4(ref xttParser))
			{
				MessageBox.Show("Incorrect Cal xtt file !");
				return false;
			}
			text = GetV4XMLPath(ref xttParser);
			FullPath = xttFileInfo.DirectoryName + "\\" + text;
		}
		else
		{
			if (!(calVersion == Cal_Version.QSC.ToString()))
			{
				MessageBox.Show("Incorrect Cal Version!");
				return false;
			}
			if (!IsXTTCalQSC(ref xttParser))
			{
				MessageBox.Show("Incorrect Cal xtt file !");
				return false;
			}
			text = GetQSCXMLPath(ref xttParser);
			FullPath = xttFileInfo.DirectoryName + "\\" + text;
		}
		if (File.Exists(FullPath))
		{
			if (calVersion == Cal_Version.V4.ToString())
			{
				File.Copy(FullPath, ProductProductPath + "\\" + ProductName + ".calv4XML", overwrite: true);
			}
			else if (calVersion == Cal_Version.QSC.ToString())
			{
				File.Copy(FullPath, ProductProductPath + "\\" + ProductName + ".calqscXML", overwrite: true);
			}
			return true;
		}
		MessageBox.Show(base.Resources["FailedToCopyV4"].ToString() + FullPath + base.Resources["DoesNotExist"].ToString() + "!", "", MessageBoxButton.OK);
		return false;
	}

	private void bnSave_Click(object sender, RoutedEventArgs e)
	{
		if (EditMode == EditModeEnum.New)
		{
			string text = txtProduct.Text;
			if (txtProduct.Text.Length == 0 || tabWWAN1.WWAN_txtXTTPath.Text.Length == 0)
			{
				MessageBox.Show(base.Resources["ProductNameEmpty"].ToString(), "");
				return;
			}
			string text2 = Path.Combine(productConfigurationFolder, txtProduct.Text);
			if (Directory.Exists(text2))
			{
				MessageBoxResult messageBoxResult = MessageBox.Show(base.Resources["Product DirectoryExists"].ToString(), "", MessageBoxButton.YesNo);
				if (messageBoxResult == MessageBoxResult.No)
				{
					MessageBox.Show(base.Resources["NoProductFolder"].ToString(), "", MessageBoxButton.OK, MessageBoxImage.Asterisk);
					return;
				}
				try
				{
					Directory.Delete(text2, recursive: true);
				}
				catch
				{
					MessageBox.Show(base.Resources["DirectoryDeletionException"].ToString());
					return;
				}
			}
			try
			{
				Directory.CreateDirectory(text2);
			}
			catch
			{
				MessageBox.Show(base.Resources["DirectoryCreationException"].ToString());
				return;
			}
			QSPR3XTT xtt = new QSPR3XTT();
			if (!xtt.LoadRFCalXTT(tabWWAN1.WWAN_txtXTTPath.Text))
			{
				MessageBox.Show(base.Resources["FailedXTT"].ToString());
				return;
			}
			FileInfo xttFileInfo = new FileInfo(tabWWAN1.WWAN_txtXTTPath.Text);
			string text3 = tabWWAN1.cbxCalVer.SelectedItem.ToString();
			string FullPath = "";
			if (!updateWWANCalXMLInfo(xtt, xttFileInfo, text2, text, text3, ref FullPath))
			{
				return;
			}
			PCF pcf = new PCF();
			pcf.IsCatM1NBIoT = ((cbxCatM1NBIoT.IsChecked == true) ? 1 : 0);
			pcf.xtt = text + ".xtt";
			pcf.CalV4XML = ((text3 == Cal_Version.V4.ToString()) ? (text + ".calv4XML") : null);
			pcf.CalQSCXML = ((text3 == Cal_Version.QSC.ToString()) ? (text + ".calqscXML") : null);
			pcf.CalVersion = text3;
			pcf.Platform = tabWWAN1.cbxPlatform.Text;
			GetVoltageCurrentLimitFromXTT(ref xtt, ref pcf.Voltage, ref pcf.CurrentLimit);
			if (text3 == Cal_Version.V4.ToString())
			{
				if (tabWWAN1.WWAN_cbImport.IsChecked == true)
				{
					pcf.useCalV4 = 0;
					CalV4Parser calV4Parser = new CalV4Parser();
					calV4Parser.ParseCalV4File(FullPath);
					List<TxPowerAction> maxTxPowerActionFromAllTechnologies = calV4Parser.GetMaxTxPowerActionFromAllTechnologies();
					pcf.TxPowerAction = new TxPowerAction[maxTxPowerActionFromAllTechnologies.Count];
					for (int i = 0; i < maxTxPowerActionFromAllTechnologies.Count; i++)
					{
						pcf.TxPowerAction[i] = maxTxPowerActionFromAllTechnologies[i];
					}
					List<RxPowerAction> list = calV4Parser.Get_HighestGainState_RxPowerAction_FromAllTechs(0);
					pcf.PRxPowerAction = new RxPowerAction[list.Count];
					for (int j = 0; j < list.Count; j++)
					{
						pcf.PRxPowerAction[j] = list[j];
					}
					List<RxPowerAction> list2 = calV4Parser.Get_HighestGainState_RxPowerAction_FromAllTechs(1);
					pcf.DRxPowerAction = new RxPowerAction[list2.Count];
					for (int k = 0; k < list2.Count; k++)
					{
						pcf.DRxPowerAction[k] = list2[k];
					}
				}
				else
				{
					pcf.useCalV4 = 1;
				}
			}
			UpdateRefQCN(ref pcf);
			UpdateWLanConfiguration(ref pcf);
			pcf.Resources = new QRCT_modem_RF_Debug_tool.Resource[5];
			Resource[] array = new Resource[5] { resource1, resource2, resource3, resource4, resource5 };
			for (int l = 0; l < 5; l++)
			{
				pcf.Resources[l] = new QRCT_modem_RF_Debug_tool.Resource();
				pcf.Resources[l].Description = array[l].Description;
				bool flag = false;
				try
				{
					if (Uri.TryCreate(array[l].ResourceFile, UriKind.Absolute, out var result) && (result.Scheme == Uri.UriSchemeHttps || result.Scheme == Uri.UriSchemeHttp))
					{
						pcf.Resources[l].ResourceFile = array[l].ResourceFile;
					}
					else if (array[l].ResourceFile.Length > 0)
					{
						File.Copy(array[l].ResourceFile, Path.Combine(text2, Path.GetFileName(array[l].ResourceFile)), overwrite: true);
						pcf.Resources[l].ResourceFile = Path.GetFileName(array[l].ResourceFile);
					}
					else
					{
						pcf.Resources[l].ResourceFile = "";
					}
				}
				catch
				{
					pcf.Resources[l].ResourceFile = "";
					pcf.Resources[l].Description = "";
				}
			}
			UpdateMPSSandRFWHID(ref pcf);
			WritePCF(pcf);
		}
		else if (EditMode == EditModeEnum.Edit)
		{
			m_currentPCF.IsCatM1NBIoT = ((cbxCatM1NBIoT.IsChecked == true) ? 1 : 0);
			if (m_currentPCF.RefQCN != tabWWAN1.WWAN_txtRefQCNPath.Text)
			{
				UpdateRefQCN(ref m_currentPCF);
			}
			if (m_currentPCF.xtt != tabWWAN1.WWAN_txtXTTPath.Text)
			{
				UpdateXTT(ref m_currentPCF);
			}
			UpdateWLanConfiguration(ref m_currentPCF);
			UpdateMPSSandRFWHID(ref m_currentPCF);
			m_currentPCF.Platform = tabWWAN1.cbxPlatform.Text;
			WritePCF(m_currentPCF);
		}
	}

	private void UpdateWLanConfiguration(ref PCF pcf)
	{
		pcf.WLANConfiguraion = new WLANInfo();
		if (tabWLAN1.AllWlanTab_cbxChipID.SelectedItem != null)
		{
			pcf.WLANConfiguraion.WCNchipID = tabWLAN1.AllWlanTab_cbxChipID.SelectedItem.ToString();
			if (WCN36xxStatic.chipMap.Keys.Contains(pcf.WLANConfiguraion.WCNchipID) && WCN36xxStatic.chipMap[pcf.WLANConfiguraion.WCNchipID] == "WCN36xx")
			{
				tabWLAN1.tabWCN36xx.updateWCN36xxInfoForPCF(ref pcf.WLANConfiguraion.WCN36xxConfig);
			}
			else if (pcf.WLANConfiguraion.WCNchipID == WCN39XXStatic.chipSeriesName)
			{
				tabWLAN1.tabWCN39xx.updateWCN39xxInfoForPCF(ref pcf.WLANConfiguraion.WCN39xxConfig);
			}
		}
	}

	private void UpdateRefQCN(ref PCF pcf)
	{
		if (tabWWAN1.WWAN_txtRefQCNPath.Text.Length > 0)
		{
			string path = Path.Combine(productConfigurationFolder, txtProduct.Text);
			if (File.Exists(tabWWAN1.WWAN_txtRefQCNPath.Text))
			{
				File.Copy(tabWWAN1.WWAN_txtRefQCNPath.Text, Path.Combine(path, Path.GetFileName(tabWWAN1.WWAN_txtRefQCNPath.Text)));
			}
			pcf.RefQCN = Path.GetFileName(tabWWAN1.WWAN_txtRefQCNPath.Text);
		}
	}

	public void passPhoneHandle(Phone phone)
	{
		tabWLAN1.tabWCN36xx.phone = phone;
	}

	private void UpdateXTT(ref PCF pcf)
	{
		string text = txtProduct.Text;
		string productProductPath = Path.Combine(productConfigurationFolder, txtProduct.Text);
		QSPR3XTT xtt = new QSPR3XTT();
		if (!xtt.LoadRFCalXTT(tabWWAN1.WWAN_txtXTTPath.Text))
		{
			MessageBox.Show(base.Resources["FailedXTT"].ToString());
			return;
		}
		FileInfo xttFileInfo = new FileInfo(tabWWAN1.WWAN_txtXTTPath.Text);
		string FullPath = "";
		if (!updateWWANCalXMLInfo(xtt, xttFileInfo, productProductPath, text, pcf.CalVersion, ref FullPath))
		{
			return;
		}
		pcf.xtt = text + ".xtt";
		pcf.CalV4XML = ((pcf.CalVersion == Cal_Version.V4.ToString()) ? (text + ".calv4XML") : null);
		pcf.CalQSCXML = ((pcf.CalVersion == Cal_Version.QSC.ToString()) ? (text + ".calqscXML") : null);
		GetVoltageCurrentLimitFromXTT(ref xtt, ref pcf.Voltage, ref pcf.CurrentLimit);
		if (!(pcf.CalVersion == Cal_Version.V4.ToString()))
		{
			return;
		}
		if (tabWWAN1.WWAN_cbImport.IsChecked == true)
		{
			pcf.useCalV4 = 0;
			CalV4Parser calV4Parser = new CalV4Parser();
			calV4Parser.ParseCalV4File(FullPath);
			List<TxPowerAction> maxTxPowerActionFromAllTechnologies = calV4Parser.GetMaxTxPowerActionFromAllTechnologies();
			pcf.TxPowerAction = new TxPowerAction[maxTxPowerActionFromAllTechnologies.Count];
			for (int i = 0; i < maxTxPowerActionFromAllTechnologies.Count; i++)
			{
				pcf.TxPowerAction[i] = maxTxPowerActionFromAllTechnologies[i];
			}
			List<RxPowerAction> list = calV4Parser.Get_HighestGainState_RxPowerAction_FromAllTechs(0);
			pcf.PRxPowerAction = new RxPowerAction[list.Count];
			for (int j = 0; j < list.Count; j++)
			{
				pcf.PRxPowerAction[j] = list[j];
			}
			List<RxPowerAction> list2 = calV4Parser.Get_HighestGainState_RxPowerAction_FromAllTechs(1);
			pcf.DRxPowerAction = new RxPowerAction[list2.Count];
			for (int k = 0; k < list2.Count; k++)
			{
				pcf.DRxPowerAction[k] = list2[k];
			}
		}
		else
		{
			pcf.useCalV4 = 1;
		}
	}

	private void UpdateMPSSandRFWHID(ref PCF pcf)
	{
		if (txtRFHWID.Text.Length > 0)
		{
			pcf.RFHWID = Convert.ToByte(txtRFHWID.Text);
		}
		else
		{
			pcf.RFHWID = 0;
		}
		pcf.MPSS = txtMPSS.Text;
	}

	private void WritePCF(PCF pcf)
	{
		string path = Path.Combine(productConfigurationFolder, txtProduct.Text);
		string text = txtProduct.Text;
		XmlSerializer xmlSerializer = new XmlSerializer(typeof(PCF));
		XmlWriter xmlWriter = XmlWriter.Create(Path.Combine(path, text + ".pcf"), new XmlWriterSettings
		{
			Indent = true
		});
		xmlSerializer.Serialize(xmlWriter, pcf);
		xmlWriter.Close();
		created();
	}

	public void GetVoltageCurrentLimitFromXTT(ref QSPR3XTT xtt, ref double voltage, ref double currentLimitA)
	{
		voltage = 3.7;
		currentLimitA = 2.0;
		int num = 0;
		for (num = 0; num < xtt.GetNumOfTests() && !(xtt.GetRealName(num) == "RFCal_InitPowerSupply"); num++)
		{
		}
		for (int i = 0; i < xtt.GetNumOfTestParameter(num); i++)
		{
			if (xtt.GetTestParameterName(num, i) == "Voltage Level")
			{
				voltage = Convert.ToDouble(xtt.GetTestParameterValue(num, i));
			}
			if (xtt.GetTestParameterName(num, i) == "Current Limit")
			{
				currentLimitA = Convert.ToDouble(xtt.GetTestParameterValue(num, i));
			}
		}
	}

	public string GetQSCXMLPath(ref QSPR3XTT xtt)
	{
		int num = 0;
		string result = "";
		for (num = 0; num < xtt.GetNumOfTests() && !(xtt.GetRealName(num) == "RFCal_ReadQSCParams"); num++)
		{
		}
		for (int i = 0; i < xtt.GetNumOfTestParameter(num); i++)
		{
			if (xtt.GetTestParameterName(num, i) == "RF Cal Input Params File")
			{
				result = xtt.GetTestParameterValue(num, i);
			}
		}
		return result;
	}

	public string GetV4XMLPath(ref QSPR3XTT xtt)
	{
		int num = 0;
		string result = "";
		for (num = 0; num < xtt.GetNumOfTests() && !(xtt.GetRealName(num) == "RFCal_CReadRFCalParams"); num++)
		{
		}
		for (int i = 0; i < xtt.GetNumOfTestParameter(num); i++)
		{
			if (xtt.GetTestParameterName(num, i) == "RF Cal Input Params File")
			{
				result = xtt.GetTestParameterValue(num, i);
			}
		}
		return result;
	}

	public bool IsXTTCalQSC(ref QSPR3XTT xtt)
	{
		bool result = false;
		for (int i = 0; i < xtt.GetNumOfTests(); i++)
		{
			if (xtt.GetRealName(i) == "RFCal_ReadQSCParams")
			{
				result = true;
				break;
			}
		}
		return result;
	}

	public bool IsXTTCalV4(ref QSPR3XTT xtt)
	{
		bool result = false;
		for (int i = 0; i < xtt.GetNumOfTests(); i++)
		{
			if (xtt.GetRealName(i) == "RFCal_CReadRFCalParams")
			{
				result = true;
				break;
			}
		}
		return result;
	}

	private void bnImport_Click(object sender, RoutedEventArgs e)
	{
		if (phone != null && phone.IsPhoneConnected())
		{
			phone.GetPhoneVersionInfo(out var SWVersion, out var _);
			txtMPSS.Text = SWVersion;
			GloVar.MPSSVersion = SWVersion;
			byte[] array = new byte[1];
			phone.NVRead(1878, array, 1);
			txtRFHWID.Text = array[0].ToString();
		}
	}

	public void SetLanguage(string culture)
	{
		ResourceDictionary resourceDictionary = new ResourceDictionary();
		try
		{
			string baseDirectory = Thread.GetDomain().BaseDirectory;
			resourceDictionary.Source = new Uri(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 SetupPCF(PCF pcf, string productName)
	{
		if (pcf == null)
		{
			return;
		}
		txtProduct.Text = productName;
		txtProduct.IsReadOnly = true;
		cbxCatM1NBIoT.IsChecked = pcf.IsCatM1NBIoT == 1;
		tabWWAN1.cbxCalVer.IsEnabled = false;
		if (tabWWAN1.cbxCalVer.Items.Contains(pcf.CalVersion))
		{
			tabWWAN1.cbxCalVer.SelectedItem = pcf.CalVersion;
		}
		tabWWAN1.WWAN_txtXTTPath.Text = pcf.xtt;
		tabWWAN1.WWAN_txtRefQCNPath.Text = pcf.RefQCN;
		txtRFHWID.Text = pcf.RFHWID.ToString();
		txtMPSS.Text = pcf.MPSS;
		resource1.txtResource.Text = pcf.Resources[0].ResourceFile;
		resource1.txtDescription.Text = pcf.Resources[0].Description;
		resource2.txtResource.Text = pcf.Resources[1].ResourceFile;
		resource2.txtDescription.Text = pcf.Resources[1].Description;
		resource3.txtResource.Text = pcf.Resources[2].ResourceFile;
		resource3.txtDescription.Text = pcf.Resources[2].Description;
		resource4.txtResource.Text = pcf.Resources[3].ResourceFile;
		resource4.txtDescription.Text = pcf.Resources[3].Description;
		resource5.txtResource.Text = pcf.Resources[4].ResourceFile;
		resource5.txtDescription.Text = pcf.Resources[4].Description;
		if (pcf.WLANConfiguraion != null && pcf.WLANConfiguraion.WCNchipID != null)
		{
			tabWLAN1.AllWlanTab_cbxChipID.SelectedItem = pcf.WLANConfiguraion.WCNchipID;
			if (WCN36xxStatic.chipMap.Keys.Contains(pcf.WLANConfiguraion.WCNchipID) && WCN36xxStatic.chipMap[pcf.WLANConfiguraion.WCNchipID] == "WCN36xx")
			{
				if (pcf.WLANConfiguraion.WCN36xxConfig != null)
				{
					tabWLAN1.tabWCN36xx.SetupUI(pcf.WLANConfiguraion.WCN36xxConfig);
				}
			}
			else if (pcf.WLANConfiguraion.WCNchipID == WCN39XXStatic.chipSeriesName && pcf.WLANConfiguraion.WCN39xxConfig != null)
			{
				tabWLAN1.tabWCN39xx.SetupUI(pcf.WLANConfiguraion.WCN39xxConfig);
			}
		}
		m_currentPCF = pcf;
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
	internal Delegate _CreateDelegate(Type delegateType, string handler)
	{
		return Delegate.CreateDelegate(delegateType, this, handler);
	}
}
