using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using Tesla.Net;
using TeslaConsole.Properties;
using WeifenLuo.WinFormsUI.Docking;

namespace TeslaConsole;

internal class SitePanel : DockContent
{
	private IContainer components;

	private NoDoubleClickTreeView tvSquadsNPods;

	private ToolStrip tsMain;

	private ToolStripButton tsbNewSquad;

	private BackgroundWorker bgwConfigurePod;

	private StatusStrip ssStatus;

	private ToolStripStatusLabel lblStatus;

	private ToolStripProgressBar pbarOpProgress;

	private Panel panel1;

	private PictureBox picPodIcon;

	private Label lblPodName;

	private Label lblPodStatus;

	private ImageList ilsBigIcons;

	private ToolTip ttTip;

	private PictureBox picRefresh;

	private ContextMenuStrip cmnuTree;

	private ToolStripMenuItem mRestartCheckedPodsIn;

	private ToolStripMenuItem mShutdownCheckedPodsIn;

	private ToolStripButton tsbManageSite;

	private System.Windows.Forms.Timer tmrPodsCheck;

	private ToolStripMenuItem mnuRemoveSquad;

	private SplitContainer splitContainer1;

	private BackgroundWorker bgwRefreshApps;

	private PictureBox picThrobber;

	private AppControlGrid grdApps;

	private ToolStripMenuItem mShutdownAllPodsIn;

	private ToolStripMenuItem mRestartAllPodsIn;

	private ToolStripDropDownButton mPowerDropDown;

	private ToolStripMenuItem mRestartAllPods;

	private ToolStripMenuItem mShutdownAllPods;

	private ToolStripSeparator mPowerSeparator;

	private ToolStripMenuItem mRestartAllCheckedPods;

	private ToolStripMenuItem mShutdownAllCheckedPods;

	private ToolStripMenuItem mnuVolume;

	private readonly Dictionary<string, NotificationAlert> mOpenConfigAlerts = new Dictionary<string, NotificationAlert>();

	private readonly Dictionary<Guid, List<PodInfo>> mSquadPodInfos = new Dictionary<Guid, List<PodInfo>>();

	private readonly Dictionary<Guid, PodInfo> mAllPods = new Dictionary<Guid, PodInfo>();

	private readonly ToolStripMenuItem[] rVolumeItems;

	private Squad mActiveSquad;

	private PodInfo mActivePod;

	private BackgroundWorker mRunningRefreshWorker;

	private int mActiveLaunchKillRequests;

	private ManualResetEvent mNoRunningLaunchKillRequests = new ManualResetEvent(initialState: true);

	private PodInfo SelectedPod
	{
		get
		{
			if (tvSquadsNPods.SelectedNode != null && tvSquadsNPods.SelectedNode.Tag is PodInfo)
			{
				return (PodInfo)tvSquadsNPods.SelectedNode.Tag;
			}
			return null;
		}
	}

	protected override void Dispose(bool disposing)
	{
		if (disposing && components != null)
		{
			components.Dispose();
		}
		base.Dispose(disposing);
	}

	private void InitializeComponent()
	{
		this.components = new System.ComponentModel.Container();
		System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TeslaConsole.SitePanel));
		this.cmnuTree = new System.Windows.Forms.ContextMenuStrip(this.components);
		this.mnuVolume = new System.Windows.Forms.ToolStripMenuItem();
		this.mRestartAllPodsIn = new System.Windows.Forms.ToolStripMenuItem();
		this.mShutdownAllPodsIn = new System.Windows.Forms.ToolStripMenuItem();
		this.mRestartCheckedPodsIn = new System.Windows.Forms.ToolStripMenuItem();
		this.mShutdownCheckedPodsIn = new System.Windows.Forms.ToolStripMenuItem();
		this.mnuRemoveSquad = new System.Windows.Forms.ToolStripMenuItem();
		this.tsMain = new System.Windows.Forms.ToolStrip();
		this.tsbNewSquad = new System.Windows.Forms.ToolStripButton();
		this.tsbManageSite = new System.Windows.Forms.ToolStripButton();
		this.mPowerDropDown = new System.Windows.Forms.ToolStripDropDownButton();
		this.mRestartAllPods = new System.Windows.Forms.ToolStripMenuItem();
		this.mShutdownAllPods = new System.Windows.Forms.ToolStripMenuItem();
		this.mPowerSeparator = new System.Windows.Forms.ToolStripSeparator();
		this.mRestartAllCheckedPods = new System.Windows.Forms.ToolStripMenuItem();
		this.mShutdownAllCheckedPods = new System.Windows.Forms.ToolStripMenuItem();
		this.bgwConfigurePod = new System.ComponentModel.BackgroundWorker();
		this.ssStatus = new System.Windows.Forms.StatusStrip();
		this.lblStatus = new System.Windows.Forms.ToolStripStatusLabel();
		this.pbarOpProgress = new System.Windows.Forms.ToolStripProgressBar();
		this.panel1 = new System.Windows.Forms.Panel();
		this.picThrobber = new System.Windows.Forms.PictureBox();
		this.lblPodStatus = new System.Windows.Forms.Label();
		this.picPodIcon = new System.Windows.Forms.PictureBox();
		this.lblPodName = new System.Windows.Forms.Label();
		this.picRefresh = new System.Windows.Forms.PictureBox();
		this.grdApps = new TeslaConsole.AppControlGrid();
		this.ilsBigIcons = new System.Windows.Forms.ImageList(this.components);
		this.ttTip = new System.Windows.Forms.ToolTip(this.components);
		this.tmrPodsCheck = new System.Windows.Forms.Timer(this.components);
		this.splitContainer1 = new System.Windows.Forms.SplitContainer();
		this.tvSquadsNPods = new TeslaConsole.NoDoubleClickTreeView();
		this.bgwRefreshApps = new System.ComponentModel.BackgroundWorker();
		this.cmnuTree.SuspendLayout();
		this.tsMain.SuspendLayout();
		this.ssStatus.SuspendLayout();
		this.panel1.SuspendLayout();
		((System.ComponentModel.ISupportInitialize)this.picThrobber).BeginInit();
		((System.ComponentModel.ISupportInitialize)this.picPodIcon).BeginInit();
		((System.ComponentModel.ISupportInitialize)this.picRefresh).BeginInit();
		this.splitContainer1.Panel1.SuspendLayout();
		this.splitContainer1.Panel2.SuspendLayout();
		this.splitContainer1.SuspendLayout();
		base.SuspendLayout();
		this.cmnuTree.Items.AddRange(new System.Windows.Forms.ToolStripItem[6] { this.mnuVolume, this.mRestartAllPodsIn, this.mShutdownAllPodsIn, this.mRestartCheckedPodsIn, this.mShutdownCheckedPodsIn, this.mnuRemoveSquad });
		this.cmnuTree.Name = "cmnuTree";
		this.cmnuTree.Size = new System.Drawing.Size(223, 158);
		this.cmnuTree.Opening += new System.ComponentModel.CancelEventHandler(cmnuTree_Opening);
		this.mnuVolume.Name = "mnuVolume";
		this.mnuVolume.Size = new System.Drawing.Size(222, 22);
		this.mnuVolume.Text = "Volume";
		this.mnuVolume.DropDownOpening += new System.EventHandler(mnuVolume_DropDownOpening);
		this.mRestartAllPodsIn.Name = "mRestartAllPodsIn";
		this.mRestartAllPodsIn.Size = new System.Drawing.Size(222, 22);
		this.mRestartAllPodsIn.Text = "Restart All Pods in";
		this.mRestartAllPodsIn.Click += new System.EventHandler(mRestartAllPodsIn_Click);
		this.mShutdownAllPodsIn.Name = "mShutdownAllPodsIn";
		this.mShutdownAllPodsIn.Size = new System.Drawing.Size(222, 22);
		this.mShutdownAllPodsIn.Text = "Shutdown All Pods in";
		this.mShutdownAllPodsIn.Click += new System.EventHandler(mShutdownAllPodsIn_Click);
		this.mRestartCheckedPodsIn.Name = "mRestartCheckedPodsIn";
		this.mRestartCheckedPodsIn.Size = new System.Drawing.Size(222, 22);
		this.mRestartCheckedPodsIn.Text = "Restart Checked Pods in";
		this.mRestartCheckedPodsIn.Click += new System.EventHandler(mRestartCheckedPodsIn_Click);
		this.mShutdownCheckedPodsIn.Name = "mShutdownCheckedPodsIn";
		this.mShutdownCheckedPodsIn.Size = new System.Drawing.Size(222, 22);
		this.mShutdownCheckedPodsIn.Text = "Shutdown Checked Pods in ";
		this.mShutdownCheckedPodsIn.Click += new System.EventHandler(mShutdownCheckedPodsIn_Click);
		this.mnuRemoveSquad.Name = "mnuRemoveSquad";
		this.mnuRemoveSquad.Size = new System.Drawing.Size(222, 22);
		this.mnuRemoveSquad.Text = "Remove Squad";
		this.mnuRemoveSquad.Click += new System.EventHandler(mnuRemoveSquad_Click);
		this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[3] { this.tsbNewSquad, this.tsbManageSite, this.mPowerDropDown });
		this.tsMain.Location = new System.Drawing.Point(0, 0);
		this.tsMain.Name = "tsMain";
		this.tsMain.Size = new System.Drawing.Size(344, 25);
		this.tsMain.TabIndex = 1;
		this.tsMain.Text = "toolStrip1";
		this.tsbNewSquad.Image = TeslaConsole.Properties.Resources.Add;
		this.tsbNewSquad.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.tsbNewSquad.Name = "tsbNewSquad";
		this.tsbNewSquad.Size = new System.Drawing.Size(87, 22);
		this.tsbNewSquad.Text = "New Squad";
		this.tsbNewSquad.Click += new System.EventHandler(tsbNewSquad_Click);
		this.tsbManageSite.Image = TeslaConsole.Properties.Resources.PodOffline16;
		this.tsbManageSite.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.tsbManageSite.Name = "tsbManageSite";
		this.tsbManageSite.Size = new System.Drawing.Size(92, 22);
		this.tsbManageSite.Text = "Manage Site";
		this.tsbManageSite.Click += new System.EventHandler(tsbManageSite_Click);
		this.mPowerDropDown.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[5] { this.mRestartAllPods, this.mShutdownAllPods, this.mPowerSeparator, this.mRestartAllCheckedPods, this.mShutdownAllCheckedPods });
		this.mPowerDropDown.Image = (System.Drawing.Image)resources.GetObject("mPowerDropDown.Image");
		this.mPowerDropDown.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.mPowerDropDown.Name = "mPowerDropDown";
		this.mPowerDropDown.Size = new System.Drawing.Size(69, 22);
		this.mPowerDropDown.Text = "Power";
		this.mRestartAllPods.Name = "mRestartAllPods";
		this.mRestartAllPods.Size = new System.Drawing.Size(206, 22);
		this.mRestartAllPods.Text = "Restart All Pods";
		this.mRestartAllPods.Click += new System.EventHandler(mRestartAllPods_Click);
		this.mShutdownAllPods.Name = "mShutdownAllPods";
		this.mShutdownAllPods.Size = new System.Drawing.Size(206, 22);
		this.mShutdownAllPods.Text = "Shutdown All Pods";
		this.mShutdownAllPods.Click += new System.EventHandler(mShutdownAllPods_Click);
		this.mPowerSeparator.Name = "mPowerSeparator";
		this.mPowerSeparator.Size = new System.Drawing.Size(203, 6);
		this.mRestartAllCheckedPods.Name = "mRestartAllCheckedPods";
		this.mRestartAllCheckedPods.Size = new System.Drawing.Size(206, 22);
		this.mRestartAllCheckedPods.Text = "Restart Checked Pods";
		this.mRestartAllCheckedPods.Click += new System.EventHandler(mRestartAllCheckedPods_Click);
		this.mShutdownAllCheckedPods.Name = "mShutdownAllCheckedPods";
		this.mShutdownAllCheckedPods.Size = new System.Drawing.Size(206, 22);
		this.mShutdownAllCheckedPods.Text = "Shutdown Checked Pods";
		this.mShutdownAllCheckedPods.Click += new System.EventHandler(mShutdownAllCheckedPods_Click);
		this.bgwConfigurePod.WorkerReportsProgress = true;
		this.bgwConfigurePod.DoWork += new System.ComponentModel.DoWorkEventHandler(bgwConfigurePod_DoWork);
		this.bgwConfigurePod.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bgwConfigurePod_RunWorkerCompleted);
		this.bgwConfigurePod.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(bgwConfigurePod_ProgressChanged);
		this.ssStatus.Items.AddRange(new System.Windows.Forms.ToolStripItem[2] { this.lblStatus, this.pbarOpProgress });
		this.ssStatus.Location = new System.Drawing.Point(0, 573);
		this.ssStatus.Name = "ssStatus";
		this.ssStatus.Size = new System.Drawing.Size(344, 22);
		this.ssStatus.TabIndex = 2;
		this.ssStatus.Text = "statusStrip1";
		this.lblStatus.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
		this.lblStatus.Name = "lblStatus";
		this.lblStatus.Size = new System.Drawing.Size(329, 17);
		this.lblStatus.Spring = true;
		this.lblStatus.Text = "Site Idle";
		this.lblStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
		this.pbarOpProgress.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
		this.pbarOpProgress.Name = "pbarOpProgress";
		this.pbarOpProgress.Size = new System.Drawing.Size(100, 16);
		this.pbarOpProgress.Visible = false;
		this.panel1.BackColor = System.Drawing.Color.White;
		this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
		this.panel1.Controls.Add(this.picThrobber);
		this.panel1.Controls.Add(this.lblPodStatus);
		this.panel1.Controls.Add(this.picPodIcon);
		this.panel1.Controls.Add(this.lblPodName);
		this.panel1.Controls.Add(this.picRefresh);
		this.panel1.Controls.Add(this.grdApps);
		this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
		this.panel1.Location = new System.Drawing.Point(0, 0);
		this.panel1.Name = "panel1";
		this.panel1.Size = new System.Drawing.Size(344, 217);
		this.panel1.TabIndex = 4;
		this.picThrobber.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.picThrobber.Image = TeslaConsole.Properties.Resources.square_throbber;
		this.picThrobber.Location = new System.Drawing.Point(293, 3);
		this.picThrobber.Name = "picThrobber";
		this.picThrobber.Size = new System.Drawing.Size(47, 32);
		this.picThrobber.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
		this.picThrobber.TabIndex = 9;
		this.picThrobber.TabStop = false;
		this.picThrobber.Visible = false;
		this.lblPodStatus.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.lblPodStatus.AutoEllipsis = true;
		this.lblPodStatus.Location = new System.Drawing.Point(41, 19);
		this.lblPodStatus.Name = "lblPodStatus";
		this.lblPodStatus.Size = new System.Drawing.Size(246, 13);
		this.lblPodStatus.TabIndex = 6;
		this.lblPodStatus.Text = "Pod is Offline";
		this.picPodIcon.Location = new System.Drawing.Point(3, 3);
		this.picPodIcon.Name = "picPodIcon";
		this.picPodIcon.Size = new System.Drawing.Size(32, 32);
		this.picPodIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
		this.picPodIcon.TabIndex = 5;
		this.picPodIcon.TabStop = false;
		this.lblPodName.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.lblPodName.AutoEllipsis = true;
		this.lblPodName.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 0);
		this.lblPodName.Location = new System.Drawing.Point(41, 3);
		this.lblPodName.Name = "lblPodName";
		this.lblPodName.Size = new System.Drawing.Size(246, 16);
		this.lblPodName.TabIndex = 4;
		this.lblPodName.Text = "Mistress Quickly";
		this.picRefresh.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.picRefresh.Cursor = System.Windows.Forms.Cursors.Hand;
		this.picRefresh.Image = (System.Drawing.Image)resources.GetObject("picRefresh.Image");
		this.picRefresh.Location = new System.Drawing.Point(308, 3);
		this.picRefresh.Name = "picRefresh";
		this.picRefresh.Size = new System.Drawing.Size(32, 32);
		this.picRefresh.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
		this.picRefresh.TabIndex = 8;
		this.picRefresh.TabStop = false;
		this.picRefresh.Click += new System.EventHandler(picRefresh_Click);
		this.grdApps.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.grdApps.Location = new System.Drawing.Point(0, 41);
		this.grdApps.Name = "grdApps";
		this.grdApps.ShowCounts = false;
		this.grdApps.Size = new System.Drawing.Size(343, 172);
		this.grdApps.TabIndex = 10;
		this.grdApps.KillApp += new System.EventHandler<TeslaConsole.AppEventArgs>(grdApps_KillApp);
		this.grdApps.LaunchApp += new System.EventHandler<TeslaConsole.AppEventArgs>(grdApps_LaunchApp);
		this.ilsBigIcons.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
		this.ilsBigIcons.ImageSize = new System.Drawing.Size(32, 32);
		this.ilsBigIcons.TransparentColor = System.Drawing.Color.Transparent;
		this.tmrPodsCheck.Enabled = true;
		this.tmrPodsCheck.Interval = 500;
		this.tmrPodsCheck.Tick += new System.EventHandler(tmrPodsCheck_Tick);
		this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
		this.splitContainer1.Location = new System.Drawing.Point(0, 25);
		this.splitContainer1.Name = "splitContainer1";
		this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
		this.splitContainer1.Panel1.Controls.Add(this.tvSquadsNPods);
		this.splitContainer1.Panel2.Controls.Add(this.panel1);
		this.splitContainer1.Size = new System.Drawing.Size(344, 548);
		this.splitContainer1.SplitterDistance = 327;
		this.splitContainer1.TabIndex = 5;
		this.tvSquadsNPods.AllowDrop = true;
		this.tvSquadsNPods.CheckBoxes = true;
		this.tvSquadsNPods.ContextMenuStrip = this.cmnuTree;
		this.tvSquadsNPods.Dock = System.Windows.Forms.DockStyle.Fill;
		this.tvSquadsNPods.LabelEdit = true;
		this.tvSquadsNPods.Location = new System.Drawing.Point(0, 0);
		this.tvSquadsNPods.Name = "tvSquadsNPods";
		this.tvSquadsNPods.Size = new System.Drawing.Size(344, 327);
		this.tvSquadsNPods.TabIndex = 0;
		this.tvSquadsNPods.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(tvSquadsNPods_AfterCheck);
		this.tvSquadsNPods.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(tvSquadsNPods_AfterLabelEdit);
		this.tvSquadsNPods.DragDrop += new System.Windows.Forms.DragEventHandler(tvSquadsNPods_DragDrop);
		this.tvSquadsNPods.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(tvSquadsNPods_AfterSelect);
		this.tvSquadsNPods.DragEnter += new System.Windows.Forms.DragEventHandler(tvSquadsNPods_DragEnter);
		this.tvSquadsNPods.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(tvSquadsNPods_NodeMouseClick);
		this.tvSquadsNPods.BeforeCheck += new System.Windows.Forms.TreeViewCancelEventHandler(tvSquadsNPods_BeforeCheck);
		this.tvSquadsNPods.KeyDown += new System.Windows.Forms.KeyEventHandler(tvSquadsNPods_KeyDown);
		this.tvSquadsNPods.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(tvSquadsNPods_ItemDrag);
		this.tvSquadsNPods.DragOver += new System.Windows.Forms.DragEventHandler(tvSquadsNPods_DragOver);
		this.bgwRefreshApps.WorkerSupportsCancellation = true;
		this.bgwRefreshApps.DoWork += new System.ComponentModel.DoWorkEventHandler(bgwRefreshPodApps_DoWork);
		this.bgwRefreshApps.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bgwRefreshApps_RunWorkerCompleted);
		base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
		base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
		base.ClientSize = new System.Drawing.Size(344, 595);
		base.Controls.Add(this.splitContainer1);
		base.Controls.Add(this.ssStatus);
		base.Controls.Add(this.tsMain);
		this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
		base.Name = "SitePanel";
		base.TabText = "PodControl";
		this.Text = "PodControl";
		base.Load += new System.EventHandler(SitePanel_Load);
		base.FormClosing += new System.Windows.Forms.FormClosingEventHandler(SitePanel_FormClosing);
		this.cmnuTree.ResumeLayout(false);
		this.tsMain.ResumeLayout(false);
		this.tsMain.PerformLayout();
		this.ssStatus.ResumeLayout(false);
		this.ssStatus.PerformLayout();
		this.panel1.ResumeLayout(false);
		((System.ComponentModel.ISupportInitialize)this.picThrobber).EndInit();
		((System.ComponentModel.ISupportInitialize)this.picPodIcon).EndInit();
		((System.ComponentModel.ISupportInitialize)this.picRefresh).EndInit();
		this.splitContainer1.Panel1.ResumeLayout(false);
		this.splitContainer1.Panel2.ResumeLayout(false);
		this.splitContainer1.ResumeLayout(false);
		base.ResumeLayout(false);
		base.PerformLayout();
	}

	public SitePanel()
	{
		InitializeComponent();
		rVolumeItems = new ToolStripMenuItem[11];
		for (int i = 0; i <= 10; i++)
		{
			int vol = i * 10;
			rVolumeItems[i] = new ToolStripMenuItem((vol > 0) ? vol.ToString() : "mute");
			rVolumeItems[i].Click += delegate
			{
				ConnectAndDo(EnumerateTreeTag(checkedOnly: false), delegate(PodInfo pi)
				{
					pi.Volume = (float)vol / 100f;
				}, "Setting Volume");
			};
		}
	}

	private void FillSite()
	{
		tvSquadsNPods.BeginUpdate();
		tvSquadsNPods.Nodes.Clear();
		mSquadPodInfos.Clear();
		foreach (Squad squad in TeslaConsole.Site.Active.Squads)
		{
			AddSquad(squad);
		}
		tvSquadsNPods.ExpandAll();
		tvSquadsNPods.EndUpdate();
		foreach (TreeNode node in tvSquadsNPods.Nodes)
		{
			foreach (TreeNode node2 in node.Nodes)
			{
				if (((PodInfo)node2.Tag).Pod.Online)
				{
					node2.Checked = true;
				}
			}
		}
	}

	private TreeNode AddSquad(Squad squad)
	{
		TreeNode treeNode = new TreeNode(squad.Name);
		treeNode.Tag = squad;
		treeNode.Checked = squad.Online;
		if (!squad.IsLocal)
		{
			SetNodeFont(treeNode, underline: false);
		}
		mSquadPodInfos.Add(squad.Guid, new List<PodInfo>());
		foreach (Pod pod in squad.Pods)
		{
			AddPod(new PodInfo(pod, register: false), treeNode);
		}
		tvSquadsNPods.Nodes.Add(treeNode);
		return treeNode;
	}

	private TreeNode NewSquad()
	{
		int num = 1;
		Squad squad = new Squad();
		squad.Name = "New Squad";
		for (int i = 0; i < TeslaConsole.Site.Active.Squads.Count; i++)
		{
			if (string.Compare(TeslaConsole.Site.Active.Squads[i].Name, squad.Name, ignoreCase: true) == 0)
			{
				squad.Name = "New Squad " + num++;
				i = -1;
			}
		}
		TeslaConsole.Site.Active.Squads.Add(squad);
		return AddSquad(squad);
	}

	private TreeNode AddPod(PodInfo pi, TreeNode squadNode)
	{
		Squad squad = squadNode.Tag as Squad;
		mSquadPodInfos[squad.Guid].Add(pi);
		pi.ConnectCompleted += Pod_ConnectCompleted;
		pi.LaunchApplicationCompleted += Pod_LaunchApplicationCompleted;
		pi.KillApplicationCompleted += Pod_KillApplicationCompleted;
		TreeNode treeNode = new TreeNode(pi.Pod.Name);
		treeNode.Tag = pi;
		string text2 = (treeNode.ImageKey = (treeNode.SelectedImageKey = Resources.PodOfflineImageKey));
		if (!pi.Pod.IsLocal)
		{
			SetNodeFont(treeNode, underline: false);
		}
		squadNode.Nodes.Add(treeNode);
		mAllPods[pi.Pod.ID] = pi;
		return treeNode;
	}

	private void SetNodeFont(TreeNode node, bool underline)
	{
		bool flag = true;
		if (node.Tag is Squad)
		{
			flag = ((Squad)node.Tag).IsLocal;
		}
		else if (node.Tag is PodInfo)
		{
			flag = ((PodInfo)node.Tag).Pod.IsLocal;
		}
		if (underline)
		{
			if (flag)
			{
				node.NodeFont = new Font(tvSquadsNPods.Font, FontStyle.Underline);
			}
			else
			{
				node.NodeFont = new Font(tvSquadsNPods.Font, FontStyle.Italic | FontStyle.Underline);
			}
		}
		else if (flag)
		{
			node.NodeFont = null;
		}
		else
		{
			node.NodeFont = new Font(tvSquadsNPods.Font, FontStyle.Italic);
		}
		node.ForeColor = (flag ? Color.Black : Color.Gray);
	}

	private void FillInfoPanel(PodInfo pod, string imageKey)
	{
		if (pod == null)
		{
			picPodIcon.Image = null;
			lblPodName.Text = "";
			lblPodStatus.Text = "";
		}
		else
		{
			picPodIcon.Image = ilsBigIcons.Images[imageKey];
			lblPodName.Text = pod.Pod.Name;
			picRefresh.Enabled = false;
			if (pod.Pod.IsLocal)
			{
				ttTip.SetToolTip(lblPodStatus, "");
				if (pod.IsConnected)
				{
					lblPodStatus.Text = "Console is connected to pod";
					lblPodStatus.ForeColor = Color.Green;
					picRefresh.Enabled = true;
				}
				else if (pod.LastConnectionException != null)
				{
					lblPodStatus.Text = "Connect error: " + pod.LastConnectionException.Message;
					ttTip.SetToolTip(lblPodStatus, lblPodStatus.Text);
					lblPodStatus.ForeColor = Color.Red;
				}
				else if (pod.IsConnecting)
				{
					lblPodStatus.Text = "Connecting...";
					ttTip.SetToolTip(lblPodStatus, lblPodStatus.Text);
					lblPodStatus.ForeColor = Color.Black;
				}
				else
				{
					lblPodStatus.Text = "Not connected";
					lblPodStatus.ForeColor = Color.DarkGray;
				}
			}
			else
			{
				lblPodStatus.Text = "Pod is not a local pod.";
				lblPodStatus.ForeColor = Color.DarkGray;
			}
		}
		RefreshAppList(pod, forceRefresh: false);
	}

	private void FillInfoPanel(Squad squad)
	{
		if (squad == null || !mSquadPodInfos.ContainsKey(squad.Guid))
		{
			picPodIcon.Image = null;
			lblPodName.Text = "";
			lblPodStatus.Text = "";
		}
		else
		{
			picPodIcon.Image = Resources.PodOffline32;
			lblPodName.Text = squad.Name;
			ttTip.SetToolTip(lblPodStatus, "");
			int num = 0;
			int num2 = 0;
			foreach (PodInfo item in mSquadPodInfos[squad.Guid])
			{
				if (item.Pod.IsLocal)
				{
					if (item.Pod.Online)
					{
						num++;
					}
					if (item.IsConnected)
					{
						num2++;
					}
				}
			}
			lblPodStatus.Text = $"{squad.Pods.Count} pods, {num} online, {num2} connected";
			lblPodStatus.ForeColor = Color.Black;
		}
		RefreshAppList(squad, forceRefresh: false);
	}

	private void RefreshAppList(PodInfo pod, bool forceRefresh)
	{
		mActiveSquad = null;
		mActivePod = null;
		grdApps.Clear();
		lblStatus.Text = "Refreshing application list...";
		lblStatus.ForeColor = Color.Black;
		if (pod == null)
		{
			picRefresh.Visible = false;
			return;
		}
		picRefresh.Show();
		picThrobber.Show();
		grdApps.ShowCounts = false;
		mActivePod = pod;
		mRunningRefreshWorker = new BackgroundWorker();
		mRunningRefreshWorker.DoWork += bgwRefreshPodApps_DoWork;
		mRunningRefreshWorker.RunWorkerCompleted += bgwRefreshApps_RunWorkerCompleted;
		mRunningRefreshWorker.RunWorkerAsync(Tuple.Create(pod, forceRefresh));
	}

	private void RefreshAppList(Squad squad, bool forceRefresh)
	{
		if (mActiveSquad == null || !(mActiveSquad.Guid == squad.Guid) || mRunningRefreshWorker == null)
		{
			mActiveSquad = null;
			mActivePod = null;
			grdApps.Clear();
			lblStatus.Text = "Refreshing application list...";
			lblStatus.ForeColor = Color.Black;
			if (squad == null || !mSquadPodInfos.ContainsKey(squad.Guid))
			{
				picRefresh.Visible = false;
				return;
			}
			picRefresh.Show();
			picThrobber.Show();
			grdApps.ShowCounts = true;
			mActiveSquad = squad;
			mRunningRefreshWorker = new BackgroundWorker();
			mRunningRefreshWorker.DoWork += bgwRefreshSquadApps_DoWork;
			mRunningRefreshWorker.RunWorkerCompleted += bgwRefreshApps_RunWorkerCompleted;
			mRunningRefreshWorker.RunWorkerAsync(Tuple.Create(squad, forceRefresh));
		}
	}

	private void IncrementActiveLaunchKillRequests()
	{
		if (mActiveLaunchKillRequests == 0)
		{
			mNoRunningLaunchKillRequests.Reset();
		}
		mActiveLaunchKillRequests++;
	}

	private void DecrementActiveLaunchKillRequests()
	{
		mActiveLaunchKillRequests--;
		if (mActiveLaunchKillRequests == 0)
		{
			mNoRunningLaunchKillRequests.Set();
		}
	}

	private void SitePanel_Load(object sender, EventArgs e)
	{
		tvSquadsNPods.ImageList = new ImageList();
		tvSquadsNPods.ImageList.Images.Add(Resources.PodOfflineImageKey, ImageCache.PodOffline16);
		tvSquadsNPods.ImageList.Images.Add(Resources.PodOnlineImageKey, ImageCache.PodOnline16);
		tvSquadsNPods.ImageList.Images.Add(Resources.PodBadImageKey, ImageCache.PodBad16);
		tvSquadsNPods.ImageList.Images.Add(Resources.PodQuestionImageKey, ImageCache.PodQuestion16);
		tvSquadsNPods.ImageList.Images.Add(Resources.PodGoImageKey, ImageCache.PodGo16);
		ilsBigIcons.Images.Add(Resources.PodOfflineImageKey, Resources.PodOffline32);
		ilsBigIcons.Images.Add(Resources.PodOnlineImageKey, Resources.PodOnline32);
		ilsBigIcons.Images.Add(Resources.PodBadImageKey, Resources.PodBad32);
		ilsBigIcons.Images.Add(Resources.PodQuestionImageKey, Resources.PodQuestion32);
		ilsBigIcons.Images.Add(Resources.PodGoImageKey, Resources.PodGo32);
		FillSite();
		PodManager.PodReadyForConfig += PodManager_PodReadyForConfig;
		PodManager.PodConfigured += PodManager_PodConfigured;
	}

	private void SitePanel_FormClosing(object sender, FormClosingEventArgs e)
	{
		tmrPodsCheck.Stop();
		PodManager.PodReadyForConfig -= PodManager_PodReadyForConfig;
		PodManager.PodConfigured -= PodManager_PodConfigured;
		foreach (TreeNode node in tvSquadsNPods.Nodes)
		{
			foreach (TreeNode node2 in node.Nodes)
			{
				PodInfo podInfo = (PodInfo)node2.Tag;
				podInfo.ConnectCompleted -= Pod_ConnectCompleted;
				podInfo.Disconnect();
			}
		}
		TeslaConsole.Site.Active.Save();
	}

	private void tsbNewSquad_Click(object sender, EventArgs e)
	{
		NewSquad().BeginEdit();
	}

	private void tsbManageSite_Click(object sender, EventArgs e)
	{
		foreach (NotificationAlert value in mOpenConfigAlerts.Values)
		{
			value.Close();
		}
		mOpenConfigAlerts.Clear();
		using (SiteManagement siteManagement = new SiteManagement())
		{
			siteManagement.ShowDialog(this);
		}
		FillSite();
	}

	private void tvSquadsNPods_BeforeCheck(object sender, TreeViewCancelEventArgs e)
	{
		if (e.Node.Tag is Squad)
		{
			e.Cancel = !((Squad)e.Node.Tag).IsLocal;
		}
		else if (e.Node.Tag is PodInfo)
		{
			e.Cancel = !((PodInfo)e.Node.Tag).Pod.IsLocal;
		}
	}

	private void tvSquadsNPods_AfterCheck(object sender, TreeViewEventArgs e)
	{
		if (e.Node.Tag is Squad)
		{
			(e.Node.Tag as Squad).Online = e.Node.Checked;
			foreach (TreeNode node in e.Node.Nodes)
			{
				if (node.Checked != e.Node.Checked)
				{
					node.Checked = e.Node.Checked;
				}
			}
			if (e.Node.IsSelected)
			{
				FillInfoPanel((Squad)e.Node.Tag);
			}
		}
		else
		{
			if (!(e.Node.Tag is PodInfo))
			{
				return;
			}
			PodInfo podInfo = (PodInfo)e.Node.Tag;
			if (e.Node.Checked)
			{
				podInfo.ConnectAsync(e.Node);
				string text2 = (e.Node.ImageKey = (e.Node.SelectedImageKey = Resources.PodQuestionImageKey));
			}
			else
			{
				podInfo.Disconnect();
				string text4 = (e.Node.ImageKey = (e.Node.SelectedImageKey = Resources.PodOfflineImageKey));
				if (e.Node.IsSelected)
				{
					FillInfoPanel(podInfo, e.Node.ImageKey);
				}
			}
			podInfo.Pod.Online = e.Node.Checked;
			if (mActiveSquad != null)
			{
				FillInfoPanel(mActiveSquad);
			}
			int num = 0;
			foreach (TreeNode node2 in e.Node.Parent.Nodes)
			{
				if (node2.Checked)
				{
					num++;
				}
			}
			if (num == e.Node.Parent.Nodes.Count)
			{
				e.Node.Parent.Checked = true;
			}
			else if (num == 0)
			{
				e.Node.Parent.Checked = false;
			}
		}
	}

	private void tvSquadsNPods_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
	{
		if (e.Label == null)
		{
			return;
		}
		if (e.Node.Tag is Squad)
		{
			foreach (Squad squad in TeslaConsole.Site.Active.Squads)
			{
				if (string.Compare(squad.Name, e.Label, ignoreCase: true) == 0)
				{
					MessageBox.Show(this, "A squad already exists with the name \"" + e.Label + "\". Squad names must be unique.", "Rename Squad", MessageBoxButtons.OK, MessageBoxIcon.Hand);
					e.CancelEdit = true;
					return;
				}
			}
			((Squad)e.Node.Tag).Name = e.Label;
		}
		else if (e.Node.Tag is PodInfo)
		{
			foreach (Squad squad2 in TeslaConsole.Site.Active.Squads)
			{
				foreach (Pod pod in squad2.Pods)
				{
					if (string.Compare(pod.Name, e.Label, ignoreCase: true) == 0)
					{
						MessageBox.Show(this, "A pod already exists with the name \"" + e.Label + "\". Pod names must be unique.", "Rename Pod", MessageBoxButtons.OK, MessageBoxIcon.Hand);
						e.CancelEdit = true;
						return;
					}
				}
			}
			((PodInfo)e.Node.Tag).Pod.Name = e.Label;
		}
		TeslaConsole.Site.Active.Save();
	}

	private void tvSquadsNPods_AfterSelect(object sender, TreeViewEventArgs e)
	{
		grdApps.Clear();
		if (e.Node == null)
		{
			FillInfoPanel(null, "");
		}
		else if (e.Node.Tag is Squad)
		{
			FillInfoPanel((Squad)e.Node.Tag);
		}
		else if (e.Node.Tag is PodInfo)
		{
			FillInfoPanel((PodInfo)e.Node.Tag, e.Node.ImageKey);
		}
	}

	private void tvSquadsNPods_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
	{
		if (e.Button == MouseButtons.Right)
		{
			tvSquadsNPods.SelectedNode = e.Node;
		}
	}

	private void PodManager_PodReadyForConfig(string requestId, byte[] macAddress)
	{
		if (base.InvokeRequired)
		{
			Invoke(new PodManager.PodReadyConfigHandler(PodManager_PodReadyForConfig), requestId, macAddress);
		}
		else if (!SiteManagement.IsOpen)
		{
			NotificationAlert notificationAlert = new NotificationAlert();
			notificationAlert.RightButtonText = "Configure";
			notificationAlert.RightButtonDialogResult = DialogResult.OK;
			notificationAlert.AlertButtonClick += ConfigAlert_AlertButtonClick;
			notificationAlert.FormClosed += ConfigAlert_FormClosed;
			notificationAlert.Tag = new Tuple<string, byte[]>(requestId, macAddress);
			mOpenConfigAlerts.Add(requestId, notificationAlert);
			Pod pod = TeslaConsole.Site.Active.FindPod(macAddress);
			if (pod != null)
			{
				notificationAlert.Title = "Configuration - " + pod.Name;
				notificationAlert.Text = pod.Name + " is ready to be configured." + Environment.NewLine + "Enter passphrase:";
				notificationAlert.ShowInput = true;
			}
			else
			{
				notificationAlert.Title = "Configuration - " + requestId;
				notificationAlert.Text = "An unrecognized pod on your site is ready to be configured.";
			}
			notificationAlert.Show();
		}
	}

	private void PodManager_PodConfigured(string requestId, byte[] macAddress)
	{
		NotificationAlert alert = null;
		if (!mOpenConfigAlerts.TryGetValue(requestId, out alert))
		{
			return;
		}
		mOpenConfigAlerts.Remove(requestId);
		if (alert.InvokeRequired)
		{
			alert.Invoke((VoidDelegate)delegate
			{
				alert.Close();
			});
		}
		else
		{
			alert.Close();
		}
	}

	private void ConfigAlert_AlertButtonClick(object sender, AlertButtonClickEventArgs e)
	{
		NotificationAlert notificationAlert = sender as NotificationAlert;
		if (e.DialogResult == DialogResult.OK)
		{
			Tuple<string, byte[]> tuple = (Tuple<string, byte[]>)notificationAlert.Tag;
			mOpenConfigAlerts.Remove(tuple.A);
			notificationAlert.Close();
			if (e.Input == null)
			{
				Pod pod = new Pod();
				pod.MacAddress = tuple.B;
				SetupPod setupPod = new SetupPod(tuple.A, pod, TeslaConsole.Site.Active.Squads);
				if (setupPod.ShowDialog(this) == DialogResult.OK)
				{
					ConfigurePod(tuple.A, setupPod.Passphrase, setupPod.Pod);
					TreeNode treeNode = null;
					bool flag = false;
					if (setupPod.Squad.Guid == Guid.Empty)
					{
						treeNode = NewSquad();
						flag = true;
					}
					else
					{
						foreach (TreeNode node in tvSquadsNPods.Nodes)
						{
							if (((Squad)node.Tag).Guid == setupPod.Squad.Guid)
							{
								treeNode = node;
								break;
							}
						}
					}
					((Squad)treeNode.Tag).Pods.Add(setupPod.Pod);
					treeNode.Expand();
					tvSquadsNPods.SelectedNode = AddPod(new PodInfo(setupPod.Pod, register: false), treeNode);
					tvSquadsNPods.SelectedNode.EnsureVisible();
					if (flag)
					{
						treeNode.BeginEdit();
					}
				}
			}
			else
			{
				Pod pod2 = TeslaConsole.Site.Active.FindPod(tuple.B);
				ConfigurePod(tuple.A, e.Input.ToUpper(), pod2);
			}
		}
		notificationAlert.Dispose();
	}

	private void ConfigAlert_FormClosed(object sender, FormClosedEventArgs e)
	{
		NotificationAlert notificationAlert = sender as NotificationAlert;
		mOpenConfigAlerts.Remove(((Tuple<string, byte[]>)notificationAlert.Tag).A);
	}

	private void ConfigurePod(string requestId, string passphrase, Pod pod)
	{
		lblStatus.Text = "Configuring " + pod.Name + "...";
		pbarOpProgress.Visible = true;
		pbarOpProgress.Value = 0;
		tsbManageSite.Enabled = false;
		tsbManageSite.ToolTipText = "Configuring Pod...";
		ssStatus.Refresh();
		bgwConfigurePod.RunWorkerAsync(new Tuple<string, string, Pod>(requestId, passphrase, pod));
	}

	private void bgwConfigurePod_DoWork(object sender, DoWorkEventArgs e)
	{
		Tuple<string, string, Pod> tuple = (Tuple<string, string, Pod>)e.Argument;
		tuple.C.Key = PodManager.ConfigurePod(tuple.A, tuple.B, tuple.C);
		if (tuple.C.Key == null)
		{
			e.Result = new PodConfigurationException(tuple.C.Name + " timed out configuring.", tuple.C);
			return;
		}
		bgwConfigurePod.ReportProgress(50, "Saving site information...");
		TeslaConsole.Site.Active.Save();
		e.Result = tuple.C.Name + " configured.";
	}

	private void bgwConfigurePod_ProgressChanged(object sender, ProgressChangedEventArgs e)
	{
		pbarOpProgress.Value = e.ProgressPercentage;
		lblStatus.Text = (string)e.UserState;
	}

	private void bgwConfigurePod_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
	{
		if (e.Result is PodConfigurationException)
		{
			lblStatus.Text = ((PodConfigurationException)e.Result).Message;
		}
		else
		{
			lblStatus.Text = (string)e.Result;
		}
		pbarOpProgress.Visible = false;
		tsbManageSite.Enabled = true;
		tsbManageSite.ToolTipText = "Manage Site";
	}

	private void bgwRefreshPodApps_DoWork(object sender, DoWorkEventArgs e)
	{
		PodInfo a2 = ((Tuple<PodInfo, bool>)e.Argument).A;
		bool b = ((Tuple<PodInfo, bool>)e.Argument).B;
		if (a2 == null)
		{
			return;
		}
		mNoRunningLaunchKillRequests.WaitOne(TimeSpan.FromMinutes(1.0));
		if (!a2.IsConnected)
		{
			return;
		}
		if (b)
		{
			a2.Refresh();
		}
		List<PodAppInstance> list = new List<PodAppInstance>();
		LaunchData[] allApplications = a2.AllApplications;
		LaunchData app;
		for (int i = 0; i < allApplications.Length; i++)
		{
			app = allApplications[i];
			list.Add(new PodAppInstance
			{
				LaunchPair = app.LaunchPair,
				PodId = a2.Pod.ID,
				IsRunning = Array.Exists(a2.RunningApplications, (LaunchedAppData a) => app.LaunchPair.LaunchKey == a.LaunchKey)
			});
		}
		e.Result = list;
	}

	private void bgwRefreshSquadApps_DoWork(object sender, DoWorkEventArgs e)
	{
		Squad a2 = ((Tuple<Squad, bool>)e.Argument).A;
		bool b = ((Tuple<Squad, bool>)e.Argument).B;
		if (a2 == null)
		{
			return;
		}
		List<PodInfo> list = mSquadPodInfos[a2.Guid];
		if (list.Count <= 0)
		{
			return;
		}
		mNoRunningLaunchKillRequests.WaitOne(TimeSpan.FromMinutes(1.0));
		List<PodAppInstance> list2 = new List<PodAppInstance>();
		foreach (PodInfo item in list)
		{
			if (!item.Pod.Online || !item.IsConnected)
			{
				continue;
			}
			if (b)
			{
				item.Refresh();
			}
			LaunchData[] allApplications = item.AllApplications;
			LaunchData app;
			for (int i = 0; i < allApplications.Length; i++)
			{
				app = allApplications[i];
				list2.Add(new PodAppInstance
				{
					LaunchPair = app.LaunchPair,
					PodId = item.Pod.ID,
					IsRunning = Array.Exists(item.RunningApplications, (LaunchedAppData a) => app.LaunchPair.LaunchKey == a.LaunchKey)
				});
			}
		}
		e.Result = list2;
	}

	private void bgwRefreshApps_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
	{
		BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
		if (backgroundWorker == mRunningRefreshWorker)
		{
			picThrobber.Visible = false;
			if (e.Error != null)
			{
				lblStatus.Text = "Failed to retrieve list";
				lblStatus.ForeColor = Color.Red;
			}
			else
			{
				if (e.Result != null)
				{
					List<PodAppInstance> list = (List<PodAppInstance>)e.Result;
					grdApps.SetData(list.FindAll((PodAppInstance app) => mAllPods[app.PodId].IsConnected));
				}
				lblStatus.Text = "Site Idle";
			}
			mRunningRefreshWorker = null;
		}
		backgroundWorker.Dispose();
	}

	private void grdApps_LaunchApp(object sender, AppEventArgs e)
	{
		if (mActivePod != null)
		{
			mActivePod.LaunchApplicationAsync(e.ApplicationId, null);
			IncrementActiveLaunchKillRequests();
		}
		else
		{
			if (mActiveSquad == null || !mSquadPodInfos.ContainsKey(mActiveSquad.Guid))
			{
				return;
			}
			foreach (PodInfo item in mSquadPodInfos[mActiveSquad.Guid])
			{
				if (item.IsConnected && e.PodIds.Contains(item.Pod.ID))
				{
					item.LaunchApplicationAsync(e.ApplicationId, null);
					IncrementActiveLaunchKillRequests();
				}
			}
		}
	}

	private void grdApps_KillApp(object sender, AppEventArgs e)
	{
		if (mActivePod != null)
		{
			if (mActivePod.IsConnected)
			{
				mActivePod.KillApplicationAsync(e.ApplicationId, null);
				IncrementActiveLaunchKillRequests();
			}
			else
			{
				mActivePod.Refresh();
			}
		}
		else
		{
			if (mActiveSquad == null || !mSquadPodInfos.ContainsKey(mActiveSquad.Guid))
			{
				return;
			}
			foreach (PodInfo item in mSquadPodInfos[mActiveSquad.Guid])
			{
				if (item.IsConnected && e.PodIds.Contains(item.Pod.ID))
				{
					item.KillApplicationAsync(e.ApplicationId, null);
					IncrementActiveLaunchKillRequests();
				}
			}
		}
	}

	private void Pod_ConnectCompleted(object sender, AsyncCompletedEventArgs e)
	{
		PodInfo podInfo = sender as PodInfo;
		TreeNode treeNode = e.UserState as TreeNode;
		if (!treeNode.Checked)
		{
			return;
		}
		if (e.Error == null)
		{
			string text2 = (treeNode.ImageKey = (treeNode.SelectedImageKey = Resources.PodOnlineImageKey));
		}
		else
		{
			string text4 = (treeNode.ImageKey = (treeNode.SelectedImageKey = Resources.PodBadImageKey));
		}
		if (tvSquadsNPods.SelectedNode == null)
		{
			return;
		}
		if (tvSquadsNPods.SelectedNode.Tag is Squad)
		{
			FillInfoPanel((Squad)tvSquadsNPods.SelectedNode.Tag);
		}
		else if (tvSquadsNPods.SelectedNode.Tag is PodInfo)
		{
			PodInfo podInfo2 = (PodInfo)tvSquadsNPods.SelectedNode.Tag;
			if (podInfo2.Pod.ID == podInfo.Pod.ID)
			{
				FillInfoPanel(podInfo, treeNode.ImageKey);
			}
		}
	}

	private void Pod_LaunchApplicationCompleted(object sender, ApplicationCompletedEventArgs e)
	{
		PodLaunchedOrKilled((PodInfo)sender, e.ApplicationId, wasKilled: false, e.Error != null);
	}

	private void Pod_KillApplicationCompleted(object sender, ApplicationCompletedEventArgs e)
	{
		PodLaunchedOrKilled((PodInfo)sender, e.ApplicationId, wasKilled: true, e.Error != null);
	}

	private void PodLaunchedOrKilled(PodInfo pod, Guid appId, bool wasKilled, bool failed)
	{
		DecrementActiveLaunchKillRequests();
		if ((mActivePod == null || !(pod.Pod.ID == mActivePod.Pod.ID)) && (mActiveSquad == null || !mActiveSquad.Pods.Contains(pod.Pod)))
		{
			return;
		}
		if (wasKilled)
		{
			if (failed)
			{
				grdApps.StopAppFailed(appId, pod.Pod.Name);
			}
			else
			{
				grdApps.StopApp(pod.Pod.ID, appId);
			}
		}
		else if (failed)
		{
			grdApps.StartAppFailed(appId, pod.Pod.Name);
		}
		else
		{
			grdApps.StartApp(pod.Pod.ID, appId);
		}
	}

	private void picRefresh_Click(object sender, EventArgs e)
	{
		if (mActivePod != null)
		{
			RefreshAppList(mActivePod, forceRefresh: true);
		}
		else if (mActiveSquad != null)
		{
			RefreshAppList(mActiveSquad, forceRefresh: true);
		}
	}

	private void cmnuTree_Opening(object sender, CancelEventArgs e)
	{
		cmnuTree.Items.Clear();
		cmnuTree.Items.Add(mnuVolume);
		cmnuTree.Items.Add(new ToolStripSeparator());
		TreeNode selectedNode = tvSquadsNPods.SelectedNode;
		if (selectedNode == null)
		{
			return;
		}
		if (selectedNode.Tag is Squad)
		{
			Squad squad = (Squad)selectedNode.Tag;
			cmnuTree.Tag = squad;
			mRestartAllPodsIn.Text = "Restart All Pods in " + squad.Name;
			mShutdownAllPodsIn.Text = "Shutdown All Pods in " + squad.Name;
			mRestartCheckedPodsIn.Text = "Restart Checked Pods in " + squad.Name;
			mShutdownCheckedPodsIn.Text = "Shutdown Checked Pods in " + squad.Name;
			cmnuTree.Items.Add(mRestartAllPodsIn);
			cmnuTree.Items.Add(mShutdownAllPodsIn);
			cmnuTree.Items.Add(mRestartCheckedPodsIn);
			cmnuTree.Items.Add(mShutdownCheckedPodsIn);
			cmnuTree.Items.Add(new ToolStripSeparator());
			cmnuTree.Items.Add(mnuRemoveSquad);
		}
		else
		{
			if (!(selectedNode.Tag is PodInfo))
			{
				return;
			}
			PodInfo podInfo = (PodInfo)selectedNode.Tag;
			cmnuTree.Tag = podInfo;
			mRestartAllPodsIn.Text = "Restart " + podInfo.Pod.Name;
			mShutdownAllPodsIn.Text = "Shutdown " + podInfo.Pod.Name;
			cmnuTree.Items.Add(mRestartAllPodsIn);
			cmnuTree.Items.Add(mShutdownAllPodsIn);
			if (!podInfo.IsConnected)
			{
				return;
			}
			LaunchData[] allApplications = podInfo.AllApplications;
			if (allApplications.Length > 0)
			{
				cmnuTree.Items.Add(new ToolStripSeparator());
				LaunchData[] array = allApplications;
				for (int i = 0; i < array.Length; i++)
				{
					LaunchData launchData = array[i];
					bool flag = podInfo.IsAppRunning(launchData.LaunchPair.LaunchKey);
					cmnuTree.Items.Add((flag ? "Stop " : "Start ") + launchData.LaunchPair.DisplayName, flag ? Resources.Stop : Resources.Play, cmnuApplicationItem_Click).Tag = new Tuple<bool, LaunchPair>(flag, launchData.LaunchPair);
				}
			}
		}
	}

	private void mRestartAllPods_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateSite(checkedOnly: false), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: true);
		}, "Restarting All Pods");
	}

	private void mShutdownAllPods_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateSite(checkedOnly: false), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: false);
		}, "Shutting Down Pods");
	}

	private void mRestartAllCheckedPods_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateSite(checkedOnly: true), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: true);
		}, "Restarting Pods");
	}

	private void mShutdownAllCheckedPods_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateSite(checkedOnly: true), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: false);
		}, "Shutting Down Pods");
	}

	private void mRestartAllPodsIn_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateTreeTag(checkedOnly: false), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: true);
		}, "Restarting Pods");
	}

	private void mShutdownAllPodsIn_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateTreeTag(checkedOnly: false), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: false);
		}, "Shutting Down Pods");
	}

	private void mRestartCheckedPodsIn_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateTreeTag(checkedOnly: true), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: true);
		}, "Restarting Pods");
	}

	private void mShutdownCheckedPodsIn_Click(object sender, EventArgs e)
	{
		ConnectAndDo(EnumerateTreeTag(checkedOnly: true), delegate(PodInfo pi)
		{
			pi.Shutdown(restart: false);
		}, "Shutting Down Pods");
	}

	private IEnumerable<PodInfo> EnumerateSite(bool checkedOnly)
	{
		foreach (Squad squad in TeslaConsole.Site.Active.Squads)
		{
			foreach (PodInfo item in EnumerateSquad(squad, checkedOnly))
			{
				yield return item;
			}
		}
	}

	private IEnumerable<PodInfo> EnumerateTreeTag(bool checkedOnly)
	{
		if (cmnuTree.Tag is Squad)
		{
			foreach (PodInfo item in EnumerateSquad((Squad)cmnuTree.Tag, checkedOnly))
			{
				yield return item;
			}
			yield break;
		}
		if (cmnuTree.Tag is PodInfo)
		{
			yield return (PodInfo)cmnuTree.Tag;
		}
	}

	private IEnumerable<PodInfo> EnumerateSquad(Squad squad, bool checkedOnly)
	{
		if (!mSquadPodInfos.TryGetValue(squad.Guid, out var podInfos))
		{
			yield break;
		}
		foreach (PodInfo podInfo in podInfos)
		{
			if (!checkedOnly || podInfo.Pod.Online)
			{
				yield return podInfo;
			}
		}
	}

	private void ConnectAndDo(IEnumerable<PodInfo> podInfos, Action<PodInfo> action, string title)
	{
		List<PodInfo> list = new List<PodInfo>();
		foreach (PodInfo podInfo in podInfos)
		{
			if (MakeChecked(podInfo, tvSquadsNPods.Nodes))
			{
				list.Add(podInfo);
			}
		}
		PodActionDialog.Show(list, action, title);
	}

	private bool MakeChecked(PodInfo podInfo, TreeNodeCollection nodes)
	{
		foreach (TreeNode node in nodes)
		{
			if (object.ReferenceEquals(node.Tag, podInfo))
			{
				if (!node.Checked)
				{
					node.Checked = true;
				}
				return true;
			}
			if (MakeChecked(podInfo, node.Nodes))
			{
				return true;
			}
		}
		return false;
	}

	private void GetConnectedPodNodes(TreeNodeCollection nodes, List<TreeNode> connectedPods)
	{
		foreach (TreeNode node in nodes)
		{
			if (node.Tag is Squad)
			{
				GetConnectedPodNodes(node.Nodes, connectedPods);
				continue;
			}
			PodInfo podInfo = (PodInfo)node.Tag;
			if (podInfo.IsConnected)
			{
				connectedPods.Add(node);
			}
		}
	}

	private void mnuRemoveSquad_Click(object sender, EventArgs e)
	{
		if (tvSquadsNPods.SelectedNode != null)
		{
			Squad squad = (Squad)tvSquadsNPods.SelectedNode.Tag;
			if (squad.Pods.Count == 0 || MessageBox.Show(this, "Removing this squad will remove the pods it contains as well. Are you sure you want to continue?", "Remove Squad", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				tvSquadsNPods.SelectedNode.Remove();
				TeslaConsole.Site.Active.Squads.Remove(squad);
				mSquadPodInfos.Remove(squad.Guid);
			}
		}
	}

	private void cmnuApplicationItem_Click(object sender, EventArgs e)
	{
		ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;
		PodInfo podInfo = cmnuTree.Tag as PodInfo;
		Tuple<bool, LaunchPair> tuple = (Tuple<bool, LaunchPair>)toolStripMenuItem.Tag;
		if (tuple.A)
		{
			podInfo.KillApplicationAsync(tuple.B.LaunchKey, null);
			toolStripMenuItem.Text = "Start " + tuple.B.DisplayName;
			toolStripMenuItem.Image = Resources.Play;
			return;
		}
		podInfo.LaunchApplicationAsync(tuple.B.LaunchKey, null);
		toolStripMenuItem.Text = "Stop " + tuple.B.DisplayName;
		toolStripMenuItem.Image = Resources.Stop;
		if (tuple.B.LaunchKey == SiteManagement.RPAppGuid || tuple.B.LaunchKey == SiteManagement.MW4AppGuid)
		{
			podInfo.Pod.HostType = HostType.GameMachineHostType;
		}
		else if (tuple.B.LaunchKey == SiteManagement.RPLCAppGuid || tuple.B.LaunchKey == SiteManagement.RPMRAppGuid || tuple.B.LaunchKey == SiteManagement.MW4LCAppGuid)
		{
			podInfo.Pod.HostType = HostType.MissionReviewHostType;
		}
	}

	private void mnuVolume_DropDownOpening(object sender, EventArgs e)
	{
		PodInfo podInfo = tvSquadsNPods.SelectedNode.Tag as PodInfo;
		mnuVolume.DropDownItems.Clear();
		if (podInfo == null)
		{
			mnuVolume.DropDownItems.AddRange(rVolumeItems);
			return;
		}
		float volume = podInfo.Volume;
		if (float.IsNaN(volume))
		{
			mnuVolume.DropDownItems.Add("There was a problem accessing the pod's volume.");
			return;
		}
		int num = (int)(Math.Round((double)volume * 10.0, 0) * 10.0);
		for (int i = 0; i < rVolumeItems.Length; i++)
		{
			mnuVolume.DropDownItems.Add(rVolumeItems[i]);
			((ToolStripMenuItem)mnuVolume.DropDownItems[i]).Checked = i + 1 == num / 10;
		}
	}

	private void tmrPodsCheck_Tick(object sender, EventArgs e)
	{
		foreach (TreeNode node in tvSquadsNPods.Nodes)
		{
			foreach (TreeNode node2 in node.Nodes)
			{
				PodInfo podInfo = node2.Tag as PodInfo;
				if (node2.Checked && !podInfo.IsConnecting && !podInfo.IsConnected)
				{
					podInfo.ConnectAsync(node2);
				}
			}
		}
	}

	private void tvSquadsNPods_ItemDrag(object sender, ItemDragEventArgs e)
	{
		if (e.Button == MouseButtons.Left)
		{
			tvSquadsNPods.SelectedNode = null;
			tvSquadsNPods.Tag = null;
			DoDragDrop(e.Item, DragDropEffects.Move);
		}
	}

	private void tvSquadsNPods_DragEnter(object sender, DragEventArgs e)
	{
		e.Effect = e.AllowedEffect;
	}

	private void tvSquadsNPods_DragOver(object sender, DragEventArgs e)
	{
		Point pt = tvSquadsNPods.PointToClient(new Point(e.X, e.Y));
		TreeNode treeNode = e.Data.GetData(typeof(TreeNode)) as TreeNode;
		TreeNode treeNode2 = tvSquadsNPods.Tag as TreeNode;
		TreeNode nodeAt = tvSquadsNPods.GetNodeAt(pt);
		e.Effect = DragDropEffects.None;
		if (treeNode.Tag is PodInfo)
		{
			if (nodeAt != null)
			{
				e.Effect = e.AllowedEffect;
			}
		}
		else if (treeNode.Tag is Squad && nodeAt != null && nodeAt.Tag is Squad)
		{
			e.Effect = e.AllowedEffect;
		}
		if (treeNode2 != nodeAt)
		{
			if (treeNode2 != null)
			{
				SetNodeFont(treeNode2, underline: false);
			}
			if (nodeAt != null)
			{
				SetNodeFont(nodeAt, underline: true);
			}
			tvSquadsNPods.Tag = nodeAt;
		}
	}

	private void tvSquadsNPods_DragDrop(object sender, DragEventArgs e)
	{
		Point pt = tvSquadsNPods.PointToClient(new Point(e.X, e.Y));
		TreeNode nodeAt = tvSquadsNPods.GetNodeAt(pt);
		TreeNode treeNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
		if (!treeNode.Equals(nodeAt) && e.Effect == DragDropEffects.Move)
		{
			if (treeNode.Tag is Squad)
			{
				Squad item = (Squad)treeNode.Tag;
				Squad item2 = (Squad)nodeAt.Tag;
				TeslaConsole.Site.Active.Squads.Remove(item);
				treeNode.Remove();
				TeslaConsole.Site.Active.Squads.Insert(TeslaConsole.Site.Active.Squads.IndexOf(item2) + 1, item);
				tvSquadsNPods.Nodes.Insert(tvSquadsNPods.Nodes.IndexOf(nodeAt) + 1, treeNode);
			}
			else if (treeNode.Tag is PodInfo)
			{
				Pod pod = ((PodInfo)treeNode.Tag).Pod;
				((Squad)treeNode.Parent.Tag).Pods.Remove(pod);
				mSquadPodInfos[((Squad)treeNode.Parent.Tag).Guid].Remove((PodInfo)treeNode.Tag);
				SetNodeFont(treeNode.Parent, underline: false);
				treeNode.Remove();
				if (nodeAt.Parent == null)
				{
					nodeAt.Nodes.Insert(0, treeNode);
					((Squad)nodeAt.Tag).Pods.Insert(0, pod);
					mSquadPodInfos[((Squad)nodeAt.Tag).Guid].Add((PodInfo)treeNode.Tag);
					SetNodeFont(nodeAt, underline: false);
				}
				else
				{
					Pod pod2 = ((PodInfo)nodeAt.Tag).Pod;
					Squad squad = (Squad)nodeAt.Parent.Tag;
					nodeAt.Parent.Nodes.Insert(nodeAt.Parent.Nodes.IndexOf(nodeAt) + 1, treeNode);
					squad.Pods.Insert(squad.Pods.IndexOf(pod2) + 1, pod);
					mSquadPodInfos[squad.Guid].Add((PodInfo)treeNode.Tag);
					SetNodeFont(nodeAt.Parent, underline: false);
				}
			}
			tvSquadsNPods.SelectedNode = treeNode;
		}
		if (tvSquadsNPods.Tag != null)
		{
			((TreeNode)tvSquadsNPods.Tag).NodeFont = null;
		}
	}

	private void tvSquadsNPods_KeyDown(object sender, KeyEventArgs e)
	{
		if (e.KeyCode == Keys.F2 && tvSquadsNPods.SelectedNode != null)
		{
			tvSquadsNPods.SelectedNode.BeginEdit();
		}
	}
}
