using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using QC.QMSLPhone;
using QCRPG.Framework;
using QCRPG.TSL.ZigBee.Packets;
using QCRPG.TSL.ZigBee.Properties;

namespace QCRPG.TSL.ZigBee;

public class ZigBeeGooier : GooierBase, QCRPG.Framework.IObserver<ConnectionStateChangeInfo>, IConfigurable
{
	private struct LV_ITEM
	{
		public uint uiMask;

		public int iItem;

		public int iSubItem;

		public uint uiState;

		public uint uiStateMask;

		public string pszText;

		public int cchTextMax;

		public int iImage;

		public IntPtr lParam;

		public int iIndent;
	}

	protected enum ControlEnableMode
	{
		DEFAULT,
		CONNECTION_OPENED,
		CONNECTION_CLOSED
	}

	protected struct ZigBeeDeviceInfo
	{
		public string addressMode;

		public string address;
	}

	protected enum DeviceStatusImageIndex
	{
		DISCONNECTED,
		CONNECTED
	}

	public const int LVM_FIRST = 4096;

	public const int LVM_SETITEM = 4102;

	public const int LVIF_IMAGE = 2;

	public const int LVIF_INDENT = 16;

	public const int LVW_FIRST = 4096;

	public const int LVM_SETEXTENDEDLISTVIEWSTYLE = 4150;

	public const int LVM_GETEXTENDEDLISTVIEWSTYLE = 4151;

	public const int LVS_EX_SUBITEMIMAGES = 2;

	protected const string menuTextOpenConnection = "Open Connection";

	protected const string menuTextCloseConnection = "Close Connection";

	protected const string menuTextEnableBeacon = "Enable Beacon";

	protected const string menuTextEnableScan = "Enable Scan";

	protected const string menuTextLoadDefaultNVMFile = "Load NVM File";

	protected ZigBeeRemoteDeviceInfo zigBeeRemoteDeviceInfoList;

	protected Configurer configurer;

	protected ZigBeeAPI ZigBeeAPI;

	protected PacketListBase packetList;

	protected PacketUserControl packetUserControl;

	protected SendRawBytesUserControl SendRawBytesUserControl;

	protected ZigBeeConfigUserControl zigBeeConfigUserControl;

	protected DeviceListViewUserControl zigBeeListViewUserControl;

	protected ZigBeeMainWorkerThread ZigBeeMainWorkerThread;

	protected string localApplicationInfo;

	protected ToolStripButton toolStripButtonOpenConnection;

	protected ToolStripButton toolStripButtonCloseConnection;

	protected ToolStripStatusLabel toolStripStatusLabelEmpty;

	protected ToolStripStatusLabel toolStripStatusLabelConnectionInfo;

	protected ToolStripButton toolStripButtonLoadNvm;

	protected ToolStripButton toolStripButtonReset;

	protected ToolStripButton toolStripButtonLoadDefaultNvm;

	protected ToolStripItem setDefaultNVM;

	protected ListView zigBeeDeviceListView = new ListView();

	protected Dictionary<uint, ZigBeeDeviceInfo> connectionHandlesPerAddress = new Dictionary<uint, ZigBeeDeviceInfo>();

	protected OpenConnectionMultipleTypesForm openConnectionMultipleTypesForm = new OpenConnectionMultipleTypesForm();

	protected ZigBeeConfigSettings ZigBeeConfigSettings;

	protected bool deviceEmulationMode;

	protected DeviceEmulationModeUserControl deviceEmulationModeUserControl;

	protected DeviceEmulationModeConfigSettings deviceEmulationModeConfigSettings;

	protected PacketAutoResponder packetAutoResponder;

	protected ZigBeeDataTransferUserControl zigBeeDataTransferUserControl;

	protected SpecificPacketNotifier specificPacketNotifier;

	protected MlmeAssociate associateRequest;

	private uint assignShortAddress;

	protected ContextMenuStrip localZigBeeDeviceContextMenuStrip = new ContextMenuStrip();

	protected ContextMenuStrip remoteZigBeeDeviceContextMenuStrip = new ContextMenuStrip();

	protected ToolStripMenuItem scanToolStripMenuItem = new ToolStripMenuItem();

	protected ToolStripMenuItem associateToolStripMenuItem = new ToolStripMenuItem();

	protected ToolStripMenuItem disassociateToolStripMenuItem = new ToolStripMenuItem();

	protected ToolStripMenuItem enableBeaconMenuItem = new ToolStripMenuItem();

	public bool disconnectingDataTransfer;

	public string localDUTAddress;

	public uint channelID;

	[DllImport("user32.dll")]
	private static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

	[DllImport("user32.dll")]
	private static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, ref LV_ITEM item_info);

	[DllImport("user32.dll")]
	private new static extern bool SetWindowText(IntPtr hWnd, string lpString);

	public ZigBeeGooier(string technologyName, QCRPG.Framework.Logger logger, Configurer configurer, ZigBeeAPI ZigBeeAPI, PacketListBase packetList, ZigBeeConfigSettings ZigBeeConfigSettings, ZigBeeMainWorkerThread ZigBeeMainWorkerThread, bool deviceEmulationMode, DeviceEmulationModeConfigSettings deviceEmulationModeConfigSettings, PacketAutoResponder packetAutoResponder, SpecificPacketNotifier SpecificPacketHandler)
		: base(technologyName, logger)
	{
		this.configurer = configurer;
		this.ZigBeeAPI = ZigBeeAPI;
		this.packetList = packetList;
		this.ZigBeeConfigSettings = ZigBeeConfigSettings;
		this.ZigBeeMainWorkerThread = ZigBeeMainWorkerThread;
		this.deviceEmulationMode = deviceEmulationMode;
		this.packetAutoResponder = packetAutoResponder;
		specificPacketNotifier = SpecificPacketHandler;
		if (!deviceEmulationMode)
		{
			List<PacketBase> list = new List<PacketBase>();
			list.AddRange(packetList.Packets);
			packetUserControl = new PacketUserControl(list);
		}
		else
		{
			List<PacketBase> list2 = new List<PacketBase>();
			list2.AddRange(packetList.ResponsePackets);
			list2.AddRange(packetList.NotificationPackets);
			packetUserControl = new PacketUserControl(list2);
			this.deviceEmulationModeConfigSettings = deviceEmulationModeConfigSettings;
			deviceEmulationModeUserControl = new DeviceEmulationModeUserControl(deviceEmulationModeConfigSettings, packetAutoResponder);
		}
		packetUserControl.RegisterLogMessageObserver(logger);
		configurer.RegisterConfigurableObject(openConnectionMultipleTypesForm, "OpenConnectionMultipleTypesFormSettings");
		configurer.RegisterConfigurableObject(this, "ZigBeeGooierMultipleSettings");
		SendRawBytesUserControl = new SendRawBytesUserControl(ZigBeeMainWorkerThread);
		zigBeeConfigUserControl = new ZigBeeConfigUserControl(ZigBeeConfigSettings);
		zigBeeListViewUserControl = new DeviceListViewUserControl();
		zigBeeRemoteDeviceInfoList = new ZigBeeRemoteDeviceInfo();
		LocalZigBeeDeviceContextMenuStrip();
		RemoteZigBeeDeviceConnectionContextMenuStrip();
		zigBeeDataTransferUserControl = new ZigBeeDataTransferUserControl(ZigBeeMainWorkerThread, this, logger, ZigBeeAPI, zigBeeRemoteDeviceInfoList);
		zigBeeDataTransferUserControl.Enabled = false;
		ZigBeeAPI.RegisterReceivePacketObserver(zigBeeDataTransferUserControl);
		ZigBeeMainWorkerThread.StartupEventHandler += ZigBeeMainWorkerThread_StartupEventHandler;
		specificPacketNotifier.AddPacketNotification(typeof(McpsDataRequest), generalPacketParserForUIUpdates);
		specificPacketNotifier.AddPacketNotification(typeof(McpsDataConfirmation), generalPacketParserForUIUpdates);
		specificPacketNotifier.AddPacketNotification(typeof(McpsDataIndication), generalPacketParserForUIUpdates);
		specificPacketNotifier.AddPacketNotification(typeof(MlmeScanConfirmation), generalPacketParserForUIUpdates);
		specificPacketNotifier.AddPacketNotification(typeof(MlmeAssociateIndication), generalPacketParserForUIUpdates);
		specificPacketNotifier.AddPacketNotification(typeof(MlmeAssociateConfirmation), generalPacketParserForUIUpdates);
		specificPacketNotifier.AddPacketNotification(typeof(MlmeReset), generalPacketParserForUIUpdates);
		specificPacketNotifier.AddPacketNotification(typeof(MlmeDisassociateIndication), generalPacketParserForUIUpdates);
	}

	protected override void StartupComplete()
	{
		SetControlEnables(ControlEnableMode.DEFAULT);
		ZigBeeAPI.RegisterConnectionStateChangeInfoObserver(this);
	}

	public void ApplicationReady()
	{
		if (ZigBeeConfigSettings.OpenZigBeeConnectionOnStartup && openConnectionMultipleTypesForm.SelectedConnectionType == OpenConnectionMultipleTypesForm.ConnectionType.SERIAL)
		{
			string serialSelectedPortName = openConnectionMultipleTypesForm.SerialSelectedPortName;
			int serialSelectedDataRate = openConnectionMultipleTypesForm.SerialSelectedDataRate;
			Handshake serialSelectedHandShake = openConnectionMultipleTypesForm.SerialSelectedHandShake;
			try
			{
				ZigBeeAPI.OpenConnection(serialSelectedPortName, serialSelectedDataRate, serialSelectedHandShake);
			}
			catch (Exception ex)
			{
				logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
			}
		}
	}

	private void generalPacketParserForUIUpdates(PacketBase packet)
	{
		string text = packet.ToString();
		if (text.Contains("MlmeReset"))
		{
			UpdateZigBeeDeviceListView(null);
			zigBeeRemoteDeviceInfoList.zigBeeRemoteDevices.Clear();
		}
		else if (text.Contains("MlmeScanConfirmation"))
		{
			uint resultlistsize = ((MlmeScanConfirmation)packet).UserFields.Resultlistsize;
			for (int i = 0; i < (int)resultlistsize; i++)
			{
				DutaddressmodeEnum coordaddrmodeAsDutaddressmodeEnum = ((MlmeScanConfirmation)packet).UserFields.PandescriptorList[i].GetCoordaddrmodeAsDutaddressmodeEnum();
				ulong coordaddress = ((MlmeScanConfirmation)packet).UserFields.PandescriptorList[i].Coordaddress;
				uint coordpanid = ((MlmeScanConfirmation)packet).UserFields.PandescriptorList[i].Coordpanid;
				uint logicalchannel = ((MlmeScanConfirmation)packet).UserFields.PandescriptorList[i].Logicalchannel;
				if (coordaddrmodeAsDutaddressmodeEnum == DutaddressmodeEnum.ShortAddress_16_BIT)
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(coordaddrmodeAsDutaddressmodeEnum, coordaddress, 0uL, coordpanid, logicalchannel);
				}
				else
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(coordaddrmodeAsDutaddressmodeEnum, 0uL, coordaddress, coordpanid, logicalchannel);
				}
				ListViewItem listViewItem = new ListViewItem();
				listViewItem.ImageIndex = 0;
				if (coordaddrmodeAsDutaddressmodeEnum == DutaddressmodeEnum.ShortAddress_16_BIT)
				{
					listViewItem.Text = coordaddress.ToString("X4");
				}
				else
				{
					listViewItem.Text = coordaddress.ToString("X16");
				}
				listViewItem.SubItems.Add(coordaddrmodeAsDutaddressmodeEnum.ToString());
				UpdateZigBeeDeviceListView(listViewItem);
			}
		}
		else if (text.Contains("MlmeBeaconNotifyIndication"))
		{
			ulong coordaddress2 = ((MlmeBeaconNotifyIndication)packet).UserFields.Coordaddress;
			DutaddressmodeEnum coordaddrmodeAsDutaddressmodeEnum2 = ((MlmeBeaconNotifyIndication)packet).UserFields.GetCoordaddrmodeAsDutaddressmodeEnum();
			uint coordpanid2 = ((MlmeBeaconNotifyIndication)packet).UserFields.Coordpanid;
			uint logicalchannel2 = ((MlmeBeaconNotifyIndication)packet).UserFields.Logicalchannel;
			if (coordaddrmodeAsDutaddressmodeEnum2 == DutaddressmodeEnum.ShortAddress_16_BIT)
			{
				zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(coordaddrmodeAsDutaddressmodeEnum2, coordaddress2, 0uL, coordpanid2, logicalchannel2);
			}
			else
			{
				zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(coordaddrmodeAsDutaddressmodeEnum2, 0uL, coordaddress2, coordpanid2, logicalchannel2);
			}
			ListViewItem listViewItem2 = new ListViewItem();
			listViewItem2.ImageIndex = 0;
			if (coordaddrmodeAsDutaddressmodeEnum2 == DutaddressmodeEnum.ShortAddress_16_BIT)
			{
				listViewItem2.Text = coordaddress2.ToString("X4");
			}
			else
			{
				listViewItem2.Text = coordaddress2.ToString("X16");
			}
			listViewItem2.SubItems.Add(coordaddrmodeAsDutaddressmodeEnum2.ToString());
			UpdateZigBeeDeviceListView(listViewItem2);
		}
		else if (text.Contains("MlmeAssociateConfirmation"))
		{
			AssociationStatusEnum statusAsAssociationStatusEnum = ((MlmeAssociateConfirmation)packet).UserFields.GetStatusAsAssociationStatusEnum();
			ListViewItem listViewItem3 = new ListViewItem();
			DutaddressmodeEnum coordaddrmodeAsDutaddressmodeEnum3 = associateRequest.UserFields.GetCoordaddrmodeAsDutaddressmodeEnum();
			ulong coordaddress3 = associateRequest.UserFields.Coordaddress;
			if (coordaddrmodeAsDutaddressmodeEnum3 == DutaddressmodeEnum.ShortAddress_16_BIT)
			{
				listViewItem3.Text = coordaddress3.ToString("X4");
			}
			else
			{
				listViewItem3.Text = coordaddress3.ToString("X16");
			}
			listViewItem3.SubItems.Add(coordaddrmodeAsDutaddressmodeEnum3.ToString());
			if (statusAsAssociationStatusEnum == AssociationStatusEnum.Association_Successful)
			{
				listViewItem3.ImageIndex = 1;
				zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(coordaddress3, out var addrMode, out var _, out var panId, out var channelId);
				if (addrMode == DutaddressmodeEnum.ShortAddress_16_BIT)
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode, coordaddress3, 0uL, panId, channelId, isConnected: true);
				}
				else
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode, 0uL, coordaddress3, panId, channelId, isConnected: true);
				}
				zigBeeDataTransferUserControl.CheckEnableTxButtonForAssociatedDevice();
			}
			else
			{
				listViewItem3.ImageIndex = 0;
			}
			UpdateZigBeeDeviceListView(listViewItem3);
		}
		else if (text.Contains("MlmeAssociateIndication"))
		{
			DutaddressmodeEnum dutaddressmodeEnum = DutaddressmodeEnum.ExtendedAddress_64_BIT;
			ulong deviceaddress = ((MlmeAssociateIndication)packet).UserFields.Deviceaddress;
			try
			{
				MlmeAssociateResponse mlmeAssociateResponse = new MlmeAssociateResponse();
				mlmeAssociateResponse._UserFields.Status = 0u;
				mlmeAssociateResponse._UserFields.Deviceaddress = deviceaddress;
				ListViewItem listViewItem4 = new ListViewItem();
				listViewItem4.Text = deviceaddress.ToString("X16");
				uint num = assignShortAddress;
				if (dutaddressmodeEnum == DutaddressmodeEnum.ShortAddress_16_BIT)
				{
					mlmeAssociateResponse._UserFields.Assocshortaddress = (uint)deviceaddress;
				}
				else
				{
					mlmeAssociateResponse._UserFields.Assocshortaddress = num;
				}
				ZigBeeAPI.Send(mlmeAssociateResponse);
				listViewItem4.SubItems.Add(dutaddressmodeEnum.ToString());
				listViewItem4.ImageIndex = 0;
				specificPacketNotifier.AddPacketNotification(typeof(MlmeCommStatus), generalPacketParserForUIUpdates);
				zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(DutaddressmodeEnum.ShortAddress_16_BIT, num, deviceaddress, 0u, 0u, isConnected: true);
				UpdateZigBeeDeviceListView(listViewItem4);
			}
			catch (Exception ex)
			{
				logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
			}
		}
		else if (text.Contains("MlmeCommStatus"))
		{
			ErrorCodeEnum statusAsErrorCodeEnum = ((MlmeCommStatus)packet).UserFields.GetStatusAsErrorCodeEnum();
			DutaddressmodeEnum dstaddrmodeAsDutaddressmodeEnum = ((MlmeCommStatus)packet).UserFields.GetDstaddrmodeAsDutaddressmodeEnum();
			ulong dstaddr = ((MlmeCommStatus)packet).UserFields.Dstaddr;
			_ = ((MlmeCommStatus)packet).UserFields.Panid;
			if (statusAsErrorCodeEnum == ErrorCodeEnum.WPAN_STATUS_CODE_SUCCESS)
			{
				ListViewItem listViewItem5 = new ListViewItem();
				UpdateZigBeeDeviceListView(null);
				if (!zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(dstaddr, out var addrMode2, out var _, out var panId2, out var channelId2))
				{
					addrMode2 = dstaddrmodeAsDutaddressmodeEnum;
				}
				if (addrMode2 == DutaddressmodeEnum.ShortAddress_16_BIT)
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode2, dstaddr, 0uL, panId2, channelId2, isConnected: true);
					listViewItem5.Text = dstaddr.ToString("X4");
				}
				else
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode2, 0uL, dstaddr, panId2, channelId2, isConnected: true);
					listViewItem5.Text = dstaddr.ToString("X16");
				}
				zigBeeDataTransferUserControl.CheckEnableTxButtonForAssociatedDevice();
				listViewItem5.SubItems.Add(addrMode2.ToString());
				listViewItem5.ImageIndex = 1;
				UpdateZigBeeDeviceListView(listViewItem5);
			}
		}
		if (text.Contains("MlmeDisassociateIndication"))
		{
			ulong deviceaddress2 = ((MlmeDisassociateIndication)packet).UserFields.Deviceaddress;
			DutaddressmodeEnum dutaddressmodeEnum2 = DutaddressmodeEnum.ExtendedAddress_64_BIT;
			ListViewItem listViewItem6 = new ListViewItem();
			UpdateZigBeeDeviceListView(null);
			if (!zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(deviceaddress2, out var addrMode3, out var _, out var panId3, out var channelId3))
			{
				addrMode3 = dutaddressmodeEnum2;
			}
			if (addrMode3 == DutaddressmodeEnum.ShortAddress_16_BIT)
			{
				zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode3, deviceaddress2, 0uL, panId3, channelId3);
				listViewItem6.Text = deviceaddress2.ToString("X4");
			}
			else
			{
				zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode3, 0uL, deviceaddress2, panId3, channelId3);
				listViewItem6.Text = deviceaddress2.ToString("X16");
			}
			listViewItem6.SubItems.Add(addrMode3.ToString());
			listViewItem6.ImageIndex = 0;
			UpdateZigBeeDeviceListView(listViewItem6);
		}
	}

	public void ZigBeeUpdateConnectionStatus(ulong remoteAddress, DutaddressmodeEnum remoteAddressMode, bool isConnected)
	{
		ListViewItem listViewItem = new ListViewItem();
		listViewItem.ImageIndex = (isConnected ? 1 : 0);
		if (remoteAddressMode == DutaddressmodeEnum.ShortAddress_16_BIT)
		{
			listViewItem.Text = remoteAddress.ToString("X4");
		}
		else
		{
			listViewItem.Text = remoteAddress.ToString("X16");
		}
		listViewItem.SubItems.Add(remoteAddressMode.ToString());
		UpdateZigBeeDeviceListView(listViewItem);
	}

	protected override void AddUserControls()
	{
		userControls.Add(packetUserControl);
		userControls.Add(zigBeeConfigUserControl);
		userControls.Add(SendRawBytesUserControl);
		userControls.Add(zigBeeDataTransferUserControl);
		userControls.Add(zigBeeListViewUserControl);
		configurer.RegisterConfigurableObject(packetUserControl, "PacketUserControlSettings");
		configurer.RegisterConfigurableObject(SendRawBytesUserControl, "SendRawBytesUserControlSettings");
		configurer.RegisterConfigurableObject(zigBeeConfigUserControl, "ZigBeeConfigUserControlSettings");
		if (deviceEmulationMode)
		{
			userControls.Add(deviceEmulationModeUserControl);
			configurer.RegisterConfigurableObject(deviceEmulationModeUserControl, "DeviceEmulationModeUserControlSettings");
		}
	}

	protected override void BuildDropDownMenu()
	{
		dropDownMenu.Text = technologyName;
		AddDropDownMenuItems();
		SetDropDownMenuItemNames();
	}

	protected void AddDropDownMenuItems()
	{
		dropDownMenu.DropDownItems.Add("Open Connection", null, OpenConnectionHandler);
		dropDownMenu.DropDownItems.Add("Close Connection", null, CloseConnectionHandler);
		setDefaultNVM = dropDownMenu.DropDownItems.Add("Load NVM File", null, EnableDefaultNvmHandler);
		((ToolStripMenuItem)setDefaultNVM).Checked = true;
		dropDownMenu.DropDownItems.Add("Enable Beacon", null, EnableBeaconHandler);
		dropDownMenu.DropDownItems.Add("Enable Scan", null, EnableScanHandler);
	}

	protected void SetDropDownMenuItemNames()
	{
		for (int i = 0; i < dropDownMenu.DropDownItems.Count; i++)
		{
			dropDownMenu.DropDownItems[i].Name = dropDownMenu.DropDownItems[i].Text;
		}
	}

	protected override void BuildCustomStatusStrip()
	{
		toolStripStatusLabelEmpty = new ToolStripStatusLabel();
		toolStripStatusLabelEmpty.Spring = true;
		customToolStripStatusLabels.Add(toolStripStatusLabelEmpty);
		toolStripStatusLabelConnectionInfo = new ToolStripStatusLabel("Not Connected");
		toolStripStatusLabelConnectionInfo.BorderStyle = Border3DStyle.Etched;
		toolStripStatusLabelConnectionInfo.BorderSides = ToolStripStatusLabelBorderSides.Left;
		customToolStripStatusLabels.Add(toolStripStatusLabelConnectionInfo);
	}

	protected override void BuildCustomToolStrip()
	{
		toolStripButtonOpenConnection = new ToolStripButton(QCRPG.Framework.Resources.GetImage("OpenConnection.png"));
		toolStripButtonOpenConnection.DisplayStyle = ToolStripItemDisplayStyle.Image;
		toolStripButtonOpenConnection.AutoToolTip = true;
		toolStripButtonOpenConnection.ToolTipText = "Open a 15.4 connection";
		toolStripButtonOpenConnection.Click += OpenConnectionHandler;
		customToolStripItems.Add(toolStripButtonOpenConnection);
		toolStripButtonCloseConnection = new ToolStripButton(QCRPG.Framework.Resources.GetImage("CloseConnection.png"));
		toolStripButtonCloseConnection.DisplayStyle = ToolStripItemDisplayStyle.Image;
		toolStripButtonCloseConnection.AutoToolTip = true;
		toolStripButtonCloseConnection.ToolTipText = "Close a 15.4 connection";
		toolStripButtonCloseConnection.Click += CloseConnectionHandler;
		customToolStripItems.Add(toolStripButtonCloseConnection);
		toolStripButtonLoadDefaultNvm = new ToolStripButton(QCRPG.Framework.Resources.GetImage("LoadDefaultNvm.png"));
		toolStripButtonLoadDefaultNvm.DisplayStyle = ToolStripItemDisplayStyle.Image;
		toolStripButtonLoadDefaultNvm.AutoToolTip = true;
		toolStripButtonLoadDefaultNvm.ToolTipText = "Load the default 15.4 NVM file specified in the config";
		toolStripButtonLoadDefaultNvm.Click += LoadDefaultNvmHandler;
		customToolStripItems.Add(toolStripButtonLoadDefaultNvm);
		toolStripButtonLoadNvm = new ToolStripButton(QCRPG.Framework.Resources.GetImage("LoadNvm.png"));
		toolStripButtonLoadNvm.DisplayStyle = ToolStripItemDisplayStyle.Image;
		toolStripButtonLoadNvm.AutoToolTip = true;
		toolStripButtonLoadNvm.ToolTipText = "Choose and load an 15.4 NVM file";
		toolStripButtonLoadNvm.Click += LoadNvmHandler;
		customToolStripItems.Add(toolStripButtonLoadNvm);
		toolStripButtonReset = new ToolStripButton(QCRPG.Framework.Resources.GetImage("Reset.png"));
		toolStripButtonReset.DisplayStyle = ToolStripItemDisplayStyle.Image;
		toolStripButtonReset.AutoToolTip = true;
		toolStripButtonReset.ToolTipText = "RESET";
		toolStripButtonReset.Click += resetToolStripMenuItem_Click;
		customToolStripItems.Add(toolStripButtonReset);
	}

	private void EnableDefaultNvmHandler(object sender, EventArgs e)
	{
		if (((ToolStripMenuItem)setDefaultNVM).Checked)
		{
			((ToolStripMenuItem)setDefaultNVM).Checked = false;
		}
		else
		{
			((ToolStripMenuItem)setDefaultNVM).Checked = true;
		}
		ZigBeeConfigSettings.EnableDefaultZigBeeNVM = ((ToolStripMenuItem)setDefaultNVM).Checked;
	}

	private void OpenConnectionHandler(object sender, EventArgs e)
	{
		openConnectionMultipleTypesForm.Title = "Open 15.4 Connection";
		openConnectionMultipleTypesForm.SerialShowSlaveAddress = false;
		openConnectionMultipleTypesForm.UIEnableInitAt115k = false;
		List<OpenConnectionMultipleTypesForm.ConnectionType> list = new List<OpenConnectionMultipleTypesForm.ConnectionType>();
		list.Add(OpenConnectionMultipleTypesForm.ConnectionType.SERIAL);
		list.Add(OpenConnectionMultipleTypesForm.ConnectionType.DIAG);
		openConnectionMultipleTypesForm.SupportedConnectionTypes = list;
		openConnectionMultipleTypesForm.SerialDisplayedDataRateList = new List<int> { 300, 1200, 2400, 4800, 9600, 19200, 34800, 57600, 115200, 3000000 };
		if (openConnectionMultipleTypesForm.ShowDialog() != DialogResult.OK)
		{
			return;
		}
		if (openConnectionMultipleTypesForm.SelectedConnectionType == OpenConnectionMultipleTypesForm.ConnectionType.SERIAL)
		{
			string serialSelectedPortName = openConnectionMultipleTypesForm.SerialSelectedPortName;
			int serialSelectedDataRate = openConnectionMultipleTypesForm.SerialSelectedDataRate;
			Handshake serialSelectedHandShake = openConnectionMultipleTypesForm.SerialSelectedHandShake;
			bool sharedConnectionEnabled = openConnectionMultipleTypesForm.SharedConnectionEnabled;
			try
			{
				if (sharedConnectionEnabled)
				{
					if (!APIBase.IsSharedConnectionActiveAndOpen(serialSelectedPortName))
					{
						APIBase.OpenNewSharedSerialConnection(serialSelectedPortName, serialSelectedDataRate, serialSelectedHandShake);
					}
					ZigBeeAPI.AddToSharedSerialConnection(serialSelectedPortName);
				}
				else
				{
					ZigBeeAPI.OpenConnection(serialSelectedPortName, serialSelectedDataRate, serialSelectedHandShake);
				}
				toolStripStatusLabelConnectionInfo.Text = serialSelectedPortName.ToString() + " Baud Rate:" + serialSelectedDataRate;
			}
			catch (Exception ex)
			{
				logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
				MessageBoxes.ShowErrorBox("Error opening 15.4 serial connection");
				return;
			}
		}
		else if (openConnectionMultipleTypesForm.SelectedConnectionType == OpenConnectionMultipleTypesForm.ConnectionType.DIAG)
		{
			string diagSelectedPortName = openConnectionMultipleTypesForm.DiagSelectedPortName;
			LibraryModeEnum diagSelectedLibraryMode = openConnectionMultipleTypesForm.DiagSelectedLibraryMode;
			Phone.TargetType diagSelectedTargetType = openConnectionMultipleTypesForm.DiagSelectedTargetType;
			Phone.DiagType diagSelectedDiagType = openConnectionMultipleTypesForm.DiagSelectedDiagType;
			try
			{
				if (!APIBase.IsSharedConnectionActiveAndOpen(diagSelectedPortName))
				{
					APIBase.OpenNewSharedDiagConnection(diagSelectedPortName, diagSelectedLibraryMode, diagSelectedTargetType, diagSelectedDiagType);
				}
				ZigBeeAPI.AddToSharedDiagConnection(diagSelectedPortName, openConnectionMultipleTypesForm.DiagTypeList[(int)diagSelectedDiagType]);
				toolStripStatusLabelConnectionInfo.Text = diagSelectedPortName.ToString() + "   Mode: " + openConnectionMultipleTypesForm.DiagLibraryModeList[(int)diagSelectedLibraryMode] + "   Target: " + openConnectionMultipleTypesForm.DiagTargetTypeList[(int)diagSelectedTargetType] + "   Type: " + openConnectionMultipleTypesForm.DiagTypeList[(int)diagSelectedDiagType];
			}
			catch (Exception ex2)
			{
				logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex2));
				MessageBoxes.ShowErrorBox("Error opening 15.4 diag connection");
				return;
			}
		}
		SetControlEnables(ControlEnableMode.CONNECTION_OPENED);
		if (((ToolStripMenuItem)setDefaultNVM).Checked)
		{
			ZigBeeMainWorkerThread.WriteNvm(ZigBeeConfigSettings.DefaultZigBeeNVMFile);
		}
		UpdateZigBeeDeviceListView(null);
	}

	private void CloseConnectionHandler(object sender, EventArgs e)
	{
		try
		{
			bool flag = openConnectionMultipleTypesForm.SelectedConnectionType == OpenConnectionMultipleTypesForm.ConnectionType.DIAG;
			string portName = (flag ? openConnectionMultipleTypesForm.DiagSelectedPortName : openConnectionMultipleTypesForm.SerialSelectedPortName);
			if (openConnectionMultipleTypesForm.SharedConnectionEnabled)
			{
				APIBase.CloseSharedSerialConnection(portName);
			}
			else if (flag)
			{
				APIBase.CloseSharedDiagConnection(portName);
			}
			else
			{
				ZigBeeAPI.CloseConnection();
			}
			toolStripStatusLabelConnectionInfo.Text = "Not Connected";
		}
		catch (Exception ex)
		{
			logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
			MessageBoxes.ShowErrorBox("Error closing 15.4 connection");
			SetControlEnables(ControlEnableMode.CONNECTION_CLOSED);
			return;
		}
		SetControlEnables(ControlEnableMode.CONNECTION_CLOSED);
	}

	private void EnableBeaconHandler(object sender, EventArgs e)
	{
		try
		{
			ZigBeeBeaconParameters zigBeeBeaconParameters = new ZigBeeBeaconParameters();
			zigBeeBeaconParameters.ChannelId = 20u;
			zigBeeBeaconParameters.PanId = 6826u;
			zigBeeBeaconParameters.SuperFrameOrder = 15u;
			zigBeeBeaconParameters.BeaconOrder = 15u;
			zigBeeBeaconParameters.IsPanCoordinator = true;
			zigBeeBeaconParameters.AssignShortAddress = 3u;
			zigBeeBeaconParameters.ShowDialog();
			if (zigBeeBeaconParameters.DialogResult == DialogResult.OK)
			{
				assignShortAddress = zigBeeBeaconParameters.AssignShortAddress;
				MlmeStart mlmeStart = new MlmeStart();
				mlmeStart._UserFields.Panid = zigBeeBeaconParameters.PanId;
				mlmeStart._UserFields.Logicalchannel = zigBeeBeaconParameters.ChannelId;
				mlmeStart._UserFields.Beaconorder = zigBeeBeaconParameters.BeaconOrder;
				mlmeStart._UserFields.Pancoordinator = (zigBeeBeaconParameters.IsPanCoordinator ? 1u : 0u);
				mlmeStart._UserFields.Superframeorder = zigBeeBeaconParameters.SuperFrameOrder;
				specificPacketNotifier.AddPacketNotification(typeof(MlmeStartConfirmation), generalPacketParserForUIUpdates);
				ZigBeeAPI.Send(mlmeStart);
			}
		}
		catch (Exception ex)
		{
			logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
		}
	}

	private void EnableAssociationHandler(object sender, EventArgs e)
	{
		try
		{
			MlmeSet mlmeSet = new MlmeSet();
			mlmeSet._UserFields.Pibattribute = 65u;
			mlmeSet._UserFields.Pibattributeindex = 0u;
			mlmeSet._UserFields.Pibattributelength = 1u;
			mlmeSet._UserFields.PibattributevalueList.Add(1u);
			specificPacketNotifier.AddPacketNotification(typeof(MlmeStartConfirmation), generalPacketParserForUIUpdates);
			ZigBeeAPI.Send(mlmeSet);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
		}
	}

	private void EnableScanHandler(object sender, EventArgs e)
	{
		UpdateZigBeeDeviceListView(null);
		zigBeeRemoteDeviceInfoList.zigBeeRemoteDevices.Clear();
		try
		{
			MlmeScan mlmeScan = new MlmeScan();
			mlmeScan._UserFields.Scanchannels = uint.MaxValue;
			mlmeScan._UserFields.Scantype = 1u;
			mlmeScan._UserFields.Scanduration = 1280u;
			specificPacketNotifier.AddPacketNotification(typeof(MlmeScanConfirmation), generalPacketParserForUIUpdates);
			specificPacketNotifier.AddPacketNotification(typeof(MlmeBeaconNotifyIndication), generalPacketParserForUIUpdates);
			ZigBeeAPI.Send(mlmeScan);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
		}
	}

	private void DisassociateHandler(ulong remoteAddress, uint remoteAddressMode, uint remotePanId, uint reason, uint txIndirect)
	{
		ModeAgnosticDataReceiver modeAgnosticDataReceiver = new ModeAgnosticDataReceiver(ZigBeeAPI);
		modeAgnosticDataReceiver.Startup();
		List<PacketBase> list = null;
		try
		{
			MlmeDisassociate mlmeDisassociate = new MlmeDisassociate();
			mlmeDisassociate._UserFields.Deviceaddrmode = remoteAddressMode;
			mlmeDisassociate._UserFields.Devicepanid = remotePanId;
			mlmeDisassociate._UserFields.Deviceaddress = remoteAddress;
			mlmeDisassociate._UserFields.Disassociatereason = reason;
			mlmeDisassociate._UserFields.Txindirect = txIndirect;
			ZigBeeAPI.Send(mlmeDisassociate);
			list = modeAgnosticDataReceiver.ReceiveAll(mlmeDisassociate.ExpectedResponseTypes, 3000);
			MlmeDisassociateConfirmation mlmeDisassociateConfirmation = (MlmeDisassociateConfirmation)PacketHelper.GetPacketTypeFromList(typeof(MlmeDisassociateConfirmation), list);
			int status = (int)mlmeDisassociateConfirmation.UserFields.Status;
			ListViewItem listViewItem = new ListViewItem();
			ulong num = remoteAddress;
			if (remoteAddressMode == 2)
			{
				listViewItem.Text = num.ToString("X4");
			}
			else
			{
				listViewItem.Text = num.ToString("X16");
			}
			listViewItem.SubItems.Add(((DutaddressmodeEnum)remoteAddressMode).ToString());
			if (status == 0)
			{
				listViewItem.ImageIndex = 0;
				zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(remoteAddress, out var addrMode, out var _, out var panId, out var channelId);
				if (addrMode == DutaddressmodeEnum.ShortAddress_16_BIT)
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode, remoteAddress, 0uL, panId, channelId);
				}
				else
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode, 0uL, remoteAddress, panId, channelId);
				}
			}
			else
			{
				listViewItem.ImageIndex = 1;
			}
			UpdateZigBeeDeviceListView(listViewItem);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, "Disassociation failed. " + ex));
		}
		finally
		{
			modeAgnosticDataReceiver.Shutdown();
		}
	}

	private void AssociateHandler(ulong remoteAddress, uint remoteAddressMode, uint remotePanId, uint channelId)
	{
		ModeAgnosticDataReceiver modeAgnosticDataReceiver = new ModeAgnosticDataReceiver(ZigBeeAPI);
		modeAgnosticDataReceiver.Startup();
		List<PacketBase> list = null;
		try
		{
			associateRequest = new MlmeAssociate();
			associateRequest._UserFields.Coordaddress = remoteAddress;
			associateRequest._UserFields.Coordaddrmode = remoteAddressMode;
			associateRequest._UserFields.Coordpanid = remotePanId;
			associateRequest._UserFields.Logicalchannel = channelId;
			associateRequest._UserFields.Capabilityinformation = 128u;
			ZigBeeAPI.Send(associateRequest);
			list = modeAgnosticDataReceiver.ReceiveAll(associateRequest.ExpectedResponseTypes, 3000);
			MlmeAssociateConfirmation mlmeAssociateConfirmation = (MlmeAssociateConfirmation)PacketHelper.GetPacketTypeFromList(typeof(MlmeAssociateConfirmation), list);
			int status = (int)mlmeAssociateConfirmation.UserFields.Status;
			ListViewItem listViewItem = new ListViewItem();
			DutaddressmodeEnum coordaddrmodeAsDutaddressmodeEnum = associateRequest.UserFields.GetCoordaddrmodeAsDutaddressmodeEnum();
			ulong coordaddress = associateRequest.UserFields.Coordaddress;
			if (coordaddrmodeAsDutaddressmodeEnum == DutaddressmodeEnum.ShortAddress_16_BIT)
			{
				listViewItem.Text = coordaddress.ToString("X4");
			}
			else
			{
				listViewItem.Text = coordaddress.ToString("X16");
			}
			listViewItem.SubItems.Add(coordaddrmodeAsDutaddressmodeEnum.ToString());
			if (status == 0)
			{
				listViewItem.ImageIndex = 1;
				zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(remoteAddress, out var addrMode, out var _, out var panId, out var channelId2);
				if (addrMode == DutaddressmodeEnum.ShortAddress_16_BIT)
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode, remoteAddress, 0uL, panId, channelId2, isConnected: true);
				}
				else
				{
					zigBeeRemoteDeviceInfoList.UpdateZigBeeRemoteDeviceList(addrMode, 0uL, remoteAddress, panId, channelId2, isConnected: true);
				}
			}
			else
			{
				listViewItem.ImageIndex = 0;
			}
			UpdateZigBeeDeviceListView(listViewItem);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, "Association failed. " + ex));
		}
		finally
		{
			modeAgnosticDataReceiver.Shutdown();
		}
	}

	private void LoadDefaultNvmHandler(object sender, EventArgs e)
	{
		ZigBeeMainWorkerThread.WriteNvm(ZigBeeConfigSettings.DefaultZigBeeNVMFile);
		ZigBeeMainWorkerThread.ReadAddress(DutaddressmodeEnum.ExtendedAddress_64_BIT);
	}

	private void LoadNvmHandler(object sender, EventArgs e)
	{
		OpenFileDialog openFileDialog = new OpenFileDialog();
		openFileDialog.Filter = "NVM Files (*.nvm)|*.nvm| BIN/TLV Files (*.BIN)|*.BIN|All Files (*.*)|*.*";
		if (openFileDialog.ShowDialog() == DialogResult.OK)
		{
			ZigBeeMainWorkerThread.WriteNvm(openFileDialog.FileName);
		}
	}

	private void ZigBeeMainWorkerThread_StartupEventHandler(object sender, string DUTAddress, string ApplicationInfo)
	{
		localDUTAddress = DUTAddress;
		localApplicationInfo = ApplicationInfo;
		IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;
		base.TitleBarMessage = "QCRPG   Address: " + localDUTAddress + localApplicationInfo;
		SetWindowText(hWnd, base.TitleBarMessage);
	}

	public void NotifyObserver(ConnectionStateChangeInfo connectionStateChangeInfo)
	{
		if (invokeControl == null)
		{
			UpdateControlEnablesFromConnectionStateChangeInfo(connectionStateChangeInfo);
			return;
		}
		invokeControl.BeginInvoke((MethodInvoker)delegate
		{
			UpdateControlEnablesFromConnectionStateChangeInfo(connectionStateChangeInfo);
		});
	}

	private void UpdateControlEnablesFromConnectionStateChangeInfo(ConnectionStateChangeInfo connectionStateChangeInfo)
	{
		if (connectionStateChangeInfo.openStateChanged)
		{
			if (connectionStateChangeInfo.openState)
			{
				SetControlEnables(ControlEnableMode.CONNECTION_OPENED);
			}
			else
			{
				SetControlEnables(ControlEnableMode.CONNECTION_CLOSED);
			}
		}
	}

	protected virtual void SetControlEnables(ControlEnableMode controlEnableMode)
	{
		switch (controlEnableMode)
		{
		case ControlEnableMode.DEFAULT:
			SetControlEnables(ControlEnableMode.CONNECTION_CLOSED);
			break;
		case ControlEnableMode.CONNECTION_OPENED:
			dropDownMenu.DropDownItems["Open Connection"].Enabled = false;
			toolStripButtonOpenConnection.Enabled = false;
			dropDownMenu.DropDownItems["Close Connection"].Enabled = true;
			toolStripButtonCloseConnection.Enabled = true;
			toolStripButtonLoadNvm.Enabled = true;
			zigBeeDataTransferUserControl.Enabled = true;
			dropDownMenu.DropDownItems["Load NVM File"].Enabled = true;
			toolStripButtonLoadDefaultNvm.Enabled = true;
			toolStripButtonLoadNvm.Enabled = true;
			break;
		case ControlEnableMode.CONNECTION_CLOSED:
			dropDownMenu.DropDownItems["Close Connection"].Enabled = false;
			toolStripButtonCloseConnection.Enabled = false;
			dropDownMenu.DropDownItems["Open Connection"].Enabled = true;
			toolStripButtonOpenConnection.Enabled = true;
			toolStripButtonLoadNvm.Enabled = false;
			dropDownMenu.DropDownItems["Load NVM File"].Enabled = true;
			toolStripButtonLoadDefaultNvm.Enabled = false;
			toolStripButtonLoadNvm.Enabled = false;
			break;
		default:
			throw new Exception("Unhandled control enable mode: " + controlEnableMode);
		}
	}

	public override void SetDeviceListView(ListView listView)
	{
		zigBeeDeviceListView = listView;
		zigBeeDeviceListView.Columns.Add("Address", 130);
		zigBeeDeviceListView.Columns.Add("Address mode", 40);
		ListViewItem listViewItem = new ListViewItem("Local 15.4 Devices", 2);
		listViewItem.ForeColor = Color.Blue;
		listViewItem.Font = new Font(listView.Font, FontStyle.Bold);
		zigBeeDeviceListView.Items.Add(listViewItem);
		zigBeeDeviceListView.FullRowSelect = true;
		zigBeeDeviceListView.HideSelection = true;
		zigBeeDeviceListView.MultiSelect = false;
		ImageList imageList = new ImageList();
		imageList.Images.Add(QCRPG.TSL.ZigBee.Properties.Resources.Remote);
		imageList.Images.Add(QCRPG.TSL.ZigBee.Properties.Resources.Connect);
		imageList.Images.Add(QCRPG.TSL.ZigBee.Properties.Resources.ZigBeeDevice);
		zigBeeDeviceListView.SmallImageList = imageList;
		listView.MouseUp += listView_MouseUp;
	}

	public void UpdateZigBeeDeviceListView(ListViewItem listViewItem)
	{
		if (zigBeeDeviceListView == null)
		{
			return;
		}
		if (listViewItem != null)
		{
			for (int i = 1; i < zigBeeDeviceListView.Items.Count; i++)
			{
				ListViewItem listViewItem2 = zigBeeDeviceListView.Items[i];
				ulong.TryParse(listViewItem2.Text, NumberStyles.HexNumber, null, out var result);
				zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(result, out var addrMode, out var altAddress, out var _, out var _);
				string text;
				string text2;
				if (addrMode == DutaddressmodeEnum.ExtendedAddress_64_BIT)
				{
					text = result.ToString("X16");
					text2 = altAddress.ToString("X4");
				}
				else
				{
					text = result.ToString("X4");
					text2 = altAddress.ToString("X16");
				}
				if (listViewItem.Text == text || listViewItem.Text == text2)
				{
					if (addrMode == DutaddressmodeEnum.ShortAddress_16_BIT && altAddress != 0)
					{
						listViewItem2.SubItems.Clear();
						listViewItem2.Text = text2;
						listViewItem2.SubItems.Add(DutaddressmodeEnum.ExtendedAddress_64_BIT.ToString());
					}
					else if (addrMode == DutaddressmodeEnum.ShortAddress_16_BIT)
					{
						listViewItem2.SubItems.Clear();
						listViewItem2.Text = text;
						listViewItem2.SubItems.Add(DutaddressmodeEnum.ShortAddress_16_BIT.ToString());
					}
					listViewItem2.ImageIndex = listViewItem.ImageIndex;
					return;
				}
			}
			InsertItemToListView(listViewItem);
			return;
		}
		int count = zigBeeDeviceListView.Items.Count;
		if (count >= 1)
		{
			for (int j = 1; j < count; j++)
			{
				RemoveItemAtIndexFromListView(1);
			}
		}
	}

	private void RemoveItemAtIndexFromListView(int itemIndex)
	{
		IAsyncResult asyncResult = zigBeeDeviceListView.BeginInvoke((MethodInvoker)delegate
		{
			zigBeeDeviceListView.Items.RemoveAt(itemIndex);
		});
		zigBeeDeviceListView.EndInvoke(asyncResult);
	}

	private void InsertItemToListView(int itemIndex, ListViewItem deviceItem)
	{
		IAsyncResult asyncResult = zigBeeDeviceListView.BeginInvoke((MethodInvoker)delegate
		{
			zigBeeDeviceListView.Items.Insert(itemIndex, deviceItem);
		});
		zigBeeDeviceListView.EndInvoke(asyncResult);
	}

	private void InsertItemToListView(ListViewItem deviceItem)
	{
		IAsyncResult asyncResult = zigBeeDeviceListView.BeginInvoke((MethodInvoker)delegate
		{
			bool flag = false;
			for (int i = 1; i < zigBeeDeviceListView.Items.Count; i++)
			{
				if (int.TryParse(zigBeeDeviceListView.Items[i].SubItems[1].Text.ToString().Substring(0, zigBeeDeviceListView.Items[i].SubItems[1].Text.ToString().Length - 3), out var result) && int.TryParse(deviceItem.SubItems[1].Text.Substring(0, deviceItem.SubItems[1].Text.Length - 3), out result) && int.Parse(zigBeeDeviceListView.Items[i].SubItems[1].Text.ToString().Substring(0, zigBeeDeviceListView.Items[i].SubItems[1].Text.ToString().Length - 3)) < int.Parse(deviceItem.SubItems[1].Text.Substring(0, deviceItem.SubItems[1].Text.Length - 3)))
				{
					zigBeeDeviceListView.Items.Insert(i, deviceItem);
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				zigBeeDeviceListView.Items.Insert(zigBeeDeviceListView.Items.Count, deviceItem);
			}
		});
		zigBeeDeviceListView.EndInvoke(asyncResult);
	}

	public bool CheckBTConnectionStatusByBDAddress(string bdAddress)
	{
		for (int i = 1; i < zigBeeDeviceListView.Items.Count; i++)
		{
			ListViewItem listViewItem = zigBeeDeviceListView.Items[i];
			if (listViewItem.Text == bdAddress && listViewItem.Checked)
			{
				return true;
			}
		}
		return false;
	}

	private void AddItemToListView(ListViewItem deviceItem)
	{
		IAsyncResult asyncResult = zigBeeDeviceListView.BeginInvoke((MethodInvoker)delegate
		{
			zigBeeDeviceListView.Items.Add(deviceItem);
		});
		zigBeeDeviceListView.EndInvoke(asyncResult);
	}

	public void RemoveZigBeeDevice(string address)
	{
		for (int i = 1; i < zigBeeDeviceListView.Items.Count; i++)
		{
			ListViewItem listViewItem = zigBeeDeviceListView.Items[i];
			if (listViewItem.Text == address)
			{
				RemoveItemFromListView(listViewItem);
				break;
			}
		}
	}

	private void RemoveItemFromListView(ListViewItem deviceItem)
	{
		IAsyncResult asyncResult = zigBeeDeviceListView.BeginInvoke((MethodInvoker)delegate
		{
			zigBeeDeviceListView.Items.Remove(deviceItem);
		});
		zigBeeDeviceListView.EndInvoke(asyncResult);
	}

	private void LocalZigBeeDeviceContextMenuStrip()
	{
		localZigBeeDeviceContextMenuStrip.Items.AddRange(new ToolStripItem[2] { enableBeaconMenuItem, scanToolStripMenuItem });
		localZigBeeDeviceContextMenuStrip.Name = "localDeviceContextMenuStrip";
		localZigBeeDeviceContextMenuStrip.Size = new Size(181, 148);
		scanToolStripMenuItem.Name = "scanToolStripMenuItem";
		scanToolStripMenuItem.Size = new Size(180, 22);
		scanToolStripMenuItem.Text = "Scan";
		scanToolStripMenuItem.Click += ScanToolStripMenuItem_Click;
		enableBeaconMenuItem.Name = "enableBeaconMenuItem";
		enableBeaconMenuItem.Size = new Size(180, 22);
		enableBeaconMenuItem.Text = "Enable Beacon";
		enableBeaconMenuItem.Click += EnableBeaconMenuItem_Click;
	}

	private void RemoteZigBeeDeviceConnectionContextMenuStrip()
	{
		remoteZigBeeDeviceContextMenuStrip.Items.AddRange(new ToolStripItem[2] { associateToolStripMenuItem, disassociateToolStripMenuItem });
		remoteZigBeeDeviceContextMenuStrip.Name = "deviceConnectionContextMenuStrip";
		remoteZigBeeDeviceContextMenuStrip.Size = new Size(258, 370);
		associateToolStripMenuItem.Name = "associateToolStripMenuItem";
		associateToolStripMenuItem.Size = new Size(257, 22);
		associateToolStripMenuItem.Text = "Associate";
		associateToolStripMenuItem.Click += AssociateToolStripMenuItem_Click;
		disassociateToolStripMenuItem.Name = "disassociateToolStripMenuItem";
		disassociateToolStripMenuItem.Size = new Size(257, 22);
		disassociateToolStripMenuItem.Text = "Disassociate";
		disassociateToolStripMenuItem.Click += DisassociateToolStripMenuItem_Click;
	}

	private void DisassociateToolStripMenuItem_Click(object sender, EventArgs e)
	{
		ListViewItem listViewItem = zigBeeDeviceListView.SelectedItems[0];
		ulong result = 0uL;
		if (ulong.TryParse(listViewItem.Text, NumberStyles.HexNumber, null, out result) && zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(result, out var addrMode, out var _, out var panId, out var _))
		{
			DisassociateHandler(result, (uint)addrMode, panId, 2u, 0u);
		}
	}

	private void AssociateToolStripMenuItem_Click(object sender, EventArgs e)
	{
		ListViewItem listViewItem = zigBeeDeviceListView.SelectedItems[0];
		ulong result = 0uL;
		if (ulong.TryParse(listViewItem.Text, NumberStyles.HexNumber, null, out result) && zigBeeRemoteDeviceInfoList.CheckAndGetZigBeeRemoteDeviceInfoByAddress(result, out var addrMode, out var _, out var panId, out var channelId))
		{
			AssociateHandler(result, (uint)addrMode, panId, channelId);
		}
	}

	private void ScanToolStripMenuItem_Click(object sender, EventArgs e)
	{
		EnableScanHandler(sender, e);
	}

	private void EnableBeaconMenuItem_Click(object sender, EventArgs e)
	{
		EnableBeaconHandler(sender, e);
		EnableAssociationHandler(sender, e);
	}

	private void resetToolStripMenuItem_Click(object sender, EventArgs e)
	{
		UpdateZigBeeDeviceListView(null);
		zigBeeRemoteDeviceInfoList.zigBeeRemoteDevices.Clear();
		MlmeReset mlmeReset = new MlmeReset();
		mlmeReset._UserFields.Reset = 2u;
		try
		{
			ZigBeeAPI.Send(mlmeReset);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new QCRPG.Framework.LogMessage(LogMessageType.Error, ex));
		}
	}

	private void listView_MouseUp(object sender, MouseEventArgs e)
	{
		ListView listView = sender as ListView;
		if (e.Button != MouseButtons.Right)
		{
			return;
		}
		ListViewItem itemAt = listView.GetItemAt(e.X, e.Y);
		if (itemAt == null)
		{
			return;
		}
		itemAt.Selected = true;
		if (itemAt.Text == "Local 15.4 Devices")
		{
			localZigBeeDeviceContextMenuStrip.Show(Cursor.Position);
		}
		else if (itemAt.Index >= 1)
		{
			if (itemAt.ImageIndex == 1)
			{
				associateToolStripMenuItem.Enabled = false;
				disassociateToolStripMenuItem.Enabled = true;
			}
			if (itemAt.ImageIndex == 0)
			{
				associateToolStripMenuItem.Enabled = true;
				disassociateToolStripMenuItem.Enabled = false;
			}
			remoteZigBeeDeviceContextMenuStrip.Show(Cursor.Position);
		}
	}

	public Configuration GetConfiguration()
	{
		Configuration configuration = new Configuration();
		configuration.SetBool("EnableDefaultZigBeeNVM", ZigBeeConfigSettings.EnableDefaultZigBeeNVM);
		return configuration;
	}

	public void SetConfiguration(Configuration configuration)
	{
		ZigBeeConfigSettings.EnableDefaultZigBeeNVM = configuration.GetBool("EnableDefaultZigBeeNVM", defaultValue: false);
		((ToolStripMenuItem)setDefaultNVM).Checked = ZigBeeConfigSettings.EnableDefaultZigBeeNVM;
	}

	public override void UpdateTitleBar()
	{
		SetWindowText((IntPtr)mainWindowHandle, "QCRPG-15.4");
	}
}
