using JetBrains.Annotations;
using Utf8Json;
using Webserver.LiveData;
using Webserver.Permissions;

namespace Webserver.WebAPI.APIs {
	[UsedImplicitly]
	public class ServerStats : AbsRestApi {
		private static readonly byte[] jsonKeyGameTime = JsonWriter.GetEncodedPropertyNameWithBeginObject ("gameTime");
		private static readonly byte[] jsonKeyPlayers = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("players");
		private static readonly byte[] jsonKeyHostiles = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("hostiles");
		private static readonly byte[] jsonKeyAnimals = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("animals");
		
		private static readonly byte[] jsonKeyDays = JsonWriter.GetEncodedPropertyNameWithBeginObject ("days");
		private static readonly byte[] jsonKeyHours = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("hours");
		private static readonly byte[] jsonKeyMinutes = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("minutes");

		protected override void HandleRestGet (RequestContext _context) {
			PrepareEnvelopedResult (out JsonWriter writer);
			
			writer.WriteRaw (jsonKeyGameTime);

			(int days, int hours, int minutes) = GameUtils.WorldTimeToElements (GameManager.Instance.World.worldTime);
			
			writer.WriteRaw (jsonKeyDays);
			writer.WriteInt32 (days);
			
			writer.WriteRaw (jsonKeyHours);
			writer.WriteInt32 (hours);
			
			writer.WriteRaw (jsonKeyMinutes);
			writer.WriteInt32 (minutes);
			
			writer.WriteEndObject ();

			writer.WriteRaw (jsonKeyPlayers);
			writer.WriteInt32 (GameManager.Instance.World.Players.Count);
			
			writer.WriteRaw (jsonKeyHostiles);
			writer.WriteInt32 (Hostiles.Instance.GetCount ());
			
			writer.WriteRaw (jsonKeyAnimals);
			writer.WriteInt32 (Animals.Instance.GetCount ());
			
			writer.WriteEndObject ();

			SendEnvelopedResult (_context, ref writer);
		}

		public override int DefaultPermissionLevel () => AdminWebModules.PermissionLevelGuest;
	}
}