using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Windows.Forms;

namespace Crysome.Client.Util;

internal static class ClipboardSta
{
	private static readonly BlockingCollection<Action> Queue;

	private static readonly Thread Thread;

	static ClipboardSta()
	{
		Queue = new BlockingCollection<Action>();
		Thread = new Thread(Worker)
		{
			IsBackground = true,
			Name = "CryClip"
		};
		Thread.SetApartmentState(ApartmentState.STA);
		Thread.Start();
	}

	private static void Worker()
	{
		foreach (Action item in Queue.GetConsumingEnumerable())
		{
			try
			{
				item();
			}
			catch
			{
			}
		}
	}

	public static string GetTextTruncated(int maxChars)
	{
		string[] box = new string[1];
		ManualResetEventSlim done = new ManualResetEventSlim(initialState: false);
		Queue.Add(delegate
		{
			try
			{
				if (Clipboard.ContainsText())
				{
					string text = Clipboard.GetText() ?? "";
					if (text.Length > maxChars)
					{
						text = text.Substring(0, maxChars) + "…";
					}
					box[0] = text;
				}
				else
				{
					box[0] = "";
				}
			}
			catch
			{
				box[0] = "";
			}
			finally
			{
				done.Set();
			}
		});
		done.Wait(3000);
		return box[0] ?? "";
	}
}
