using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using Webserver.Permissions;
using Webserver.SSE;

// Implemented following HTML spec
// https://html.spec.whatwg.org/multipage/server-sent-events.html

namespace Webserver.UrlHandlers {
	public class SseHandler : AbsHandler {
		private readonly Dictionary<string, AbsEvent> events = new CaseInsensitiveStringDictionary<AbsEvent> ();

		private ThreadManager.ThreadInfo queueThead;
		private readonly AutoResetEvent evSendRequest = new AutoResetEvent (false);
		private bool shutdown;

		private static readonly Type[] ctorTypes = { typeof (SseHandler) };
		private static readonly object[] ctorParams = new object[1];

		private readonly List<SseClient> clients = new List<SseClient>();

		public SseHandler (string _moduleName = null) : base (_moduleName) {
			ctorParams[0] = this;

			ReflectionHelpers.FindTypesImplementingBase (typeof (AbsEvent), apiFoundCallback);
		}

		private void apiFoundCallback (Type _type) {
			ConstructorInfo ctor = _type.GetConstructor (ctorTypes);
			if (ctor == null) {
				return;
			}

			AbsEvent apiInstance = (AbsEvent)ctor.Invoke (ctorParams);
			AddEvent (apiInstance.Name, apiInstance);
		}

		public override void SetBasePathAndParent (Web _parent, string _relativePath) {
			base.SetBasePathAndParent (_parent, _relativePath);

			queueThead = ThreadManager.StartThread ($"SSE-Processing_{urlBasePath}", QueueProcessThread, ThreadPriority.BelowNormal,
				_useRealThread: true);
		}

		public override void Shutdown () {
			base.Shutdown ();
			shutdown = true;
			SignalSendQueue ();
		}

		// ReSharper disable once MemberCanBePrivate.Global
		public void AddEvent (string _eventName, AbsEvent _eventInstance) {
			events.Add (_eventName, _eventInstance);
			AdminWebModules.Instance.AddKnownModule (new AdminWebModules.WebModule($"webevent.{_eventName}", _eventInstance.DefaultPermissionLevel (), true));
		}

		public override void HandleRequest (RequestContext _context) {
			string eventNames = _context.QueryParameters ["events"];
			if (string.IsNullOrEmpty (eventNames)) {
				Log.Warning ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): No 'events' query parameter given");
				_context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
				return;
			}

			SseClient client;
			try {
				client = new SseClient(this, _context.Response);
			} catch (Exception e) {
				Log.Error ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): Could not create client:");
				Log.Exception (e);
				_context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
				return;
			}

			int eventsFound = 0;
			int eventsAuthorized = 0;
			int eventsRegistered = 0;
			foreach (string eventName in eventNames.Split (',', StringSplitOptions.RemoveEmptyEntries)) {
				if (!events.TryGetValue (eventName, out AbsEvent eventInstance)) {
					Log.Warning ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): No handler found for event \"{eventName}\"");
					continue;
				}

				eventsFound++;
				
				if (!IsAuthorizedForEvent (eventName, _context.PermissionLevel)) {
					continue;
				}

				eventsAuthorized++;

				try
				{
					eventInstance.AddListener (client);
				} catch (Exception e) {
					Log.Error ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): Handler {eventInstance.Name} threw an exception:");
					Log.Exception (e);
					_context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
				}

				eventsRegistered++;
			}

			if (eventsFound == 0) {
				_context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
				_context.Response.Close ();
				return;
			}

			if (eventsAuthorized == 0) {
				_context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
				if (_context.Connection != null) {
					//Log.Out ($"{nameof(SseHandler)}: user '{user.SteamID}' not allowed to access '{eventName}'");
				}

				_context.Response.Close ();
				return;
			}

			clients.Add (client);
		}

		private bool IsAuthorizedForEvent (string _eventName, int _permissionLevel) {
			return AdminWebModules.Instance.ModuleAllowedWithLevel ($"webevent.{_eventName}", _permissionLevel);
		}

		private void QueueProcessThread (ThreadManager.ThreadInfo _threadInfo) {
			while (!shutdown && !_threadInfo.TerminationRequested ()) {
				evSendRequest.WaitOne (500);

				foreach ((string eventName, AbsEvent eventHandler) in events) {
					try {
						eventHandler.ProcessSendQueue ();
					} catch (Exception e) {
						Log.Error ($"[Web] [SSE] '{eventName}': Error processing send queue");
						Log.Exception (e);
					}
				}

				for (int index = clients.Count - 1; index >= 0; index--) {
					clients[index].HandleKeepAlive ();
				}
			}
		}

		public void SignalSendQueue () {
			evSendRequest.Set ();
		}

		public void ClientClosed (SseClient _client) {
			foreach ((string eventName, AbsEvent eventHandler) in events) {
				try {
					eventHandler.ClientClosed (_client);
				} catch (Exception e) {
					Log.Error($"[Web] [SSE] '{eventName}': Error closing client");
					Log.Exception(e);
				}
			}

			clients.Remove (_client);
		}
	}
}