using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

namespace Replikanto.Communicator
{
	public static class CommunicatorFactory
	{
		internal static async Task<CommunicatorBroker> Create(bool startWS = false, string parent = "")
		{
			Delegate625.smethod_0(CommunicatorFactory.semaphoreSlim_0, Delegate625.delegate625_0);
			CommunicatorBroker communicatorBroker;
			try
			{
				if (CommunicatorFactory.communicatorBroker_0 != null)
				{
					if (startWS && !CommunicatorFactory.communicatorBroker_0.Boolean_1)
					{
						TaskAwaiter taskAwaiter = Delegate632.smethod_0(CommunicatorFactory.communicatorBroker_0.StartWSConnection(), Delegate632.delegate632_0);
						if (!Delegate633.smethod_0(ref taskAwaiter, Delegate633.delegate633_0))
						{
							await taskAwaiter;
							TaskAwaiter taskAwaiter2;
							taskAwaiter = taskAwaiter2;
							taskAwaiter2 = default(TaskAwaiter);
						}
						Delegate634.smethod_0(ref taskAwaiter, Delegate634.delegate634_0);
						Delegate34.smethod_0("Replikanto: Communication ws channel enabled", 1, Delegate34.delegate34_0);
					}
				}
				else
				{
					CommunicatorFactory.communicatorBroker_0 = new CommunicatorBroker();
					if (startWS)
					{
						TaskAwaiter taskAwaiter = Delegate632.smethod_0(CommunicatorFactory.communicatorBroker_0.StartWSConnection(), Delegate632.delegate632_0);
						if (!Delegate633.smethod_0(ref taskAwaiter, Delegate633.delegate633_0))
						{
							await taskAwaiter;
							TaskAwaiter taskAwaiter2;
							taskAwaiter = taskAwaiter2;
							taskAwaiter2 = default(TaskAwaiter);
						}
						Delegate634.smethod_0(ref taskAwaiter, Delegate634.delegate634_0);
						Delegate34.smethod_0("Replikanto: Communication ws channel created", 1, Delegate34.delegate34_0);
					}
				}
				if (Delegate104.smethod_0(parent, string.Empty, Delegate104.delegate104_0))
				{
					CommunicatorFactory.uint_0 += 1U;
				}
				communicatorBroker = CommunicatorFactory.communicatorBroker_0;
			}
			finally
			{
				Delegate626.smethod_0(CommunicatorFactory.semaphoreSlim_0, Delegate626.delegate626_0);
			}
			return communicatorBroker;
		}

		internal static void Release(CommunicatorBroker communicator, string parent)
		{
			if (communicator != null)
			{
				if (Delegate104.smethod_0(parent, string.Empty, Delegate104.delegate104_0))
				{
					CommunicatorFactory.uint_0 -= 1U;
					if (CommunicatorFactory.uint_0 == 0U)
					{
						try
						{
							communicator.Stop();
						}
						catch
						{
						}
					}
				}
				return;
			}
		}

		internal static void smethod_0(object object_0)
		{
			object_0.Stop();
		}

		internal static void smethod_1()
		{
		}

		internal static void smethod_2()
		{
		}

		internal static void smethod_3()
		{
		}

		private static SemaphoreSlim semaphoreSlim_0 = new SemaphoreSlim(1, 1);

		private static CommunicatorBroker communicatorBroker_0;

		private static uint uint_0 = 0U;
	}
}
