using System.Threading;
using System.Windows.Forms;
using Crysome.Common.Network;
using Crysome.Common.Network.Packets;

namespace Crysome.Client.Handlers;

public static class ChatHandlers
{
	private static CrysomeClient _client;

	private static ChatForm _form;

	private static Thread _uiThread;

	private static readonly object _lock = new object();

	public static void HandleChatMessage(CrysomeClient client, IPacket packet)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		ChatMessagePacket val = (ChatMessagePacket)packet;
		if (string.IsNullOrEmpty(val.Message))
		{
			return;
		}
		_client = client;
		EnsureForm();
		try
		{
			_form?.AddMessage("Server", val.Message);
		}
		catch
		{
		}
	}

	internal static void OnFormClosed()
	{
		lock (_lock)
		{
			_form = null;
		}
	}

	private static void EnsureForm()
	{
		lock (_lock)
		{
			if (_form == null || _form.IsDisposed)
			{
				_form = new ChatForm(SendToServer);
				_uiThread = new Thread((ThreadStart)delegate
				{
					Application.EnableVisualStyles();
					Application.SetCompatibleTextRenderingDefault(defaultValue: false);
					Application.Run(_form);
				})
				{
					IsBackground = true
				};
				_uiThread.SetApartmentState(ApartmentState.STA);
				_uiThread.Start();
				while (_form == null || !_form.IsHandleCreated)
				{
					Thread.Sleep(50);
				}
			}
		}
	}

	private static void SendToServer(string msg)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Expected O, but got Unknown
		try
		{
			CrysomeClient client = _client;
			if (client != null && client.IsConnected)
			{
				_client.SendPacket((IPacket)new ChatMessagePacket(msg));
			}
		}
		catch
		{
		}
	}
}
