using System.Net;
using JetBrains.Annotations;
using Utf8Json;
using Webserver;
using Webserver.Permissions;
using Webserver.WebAPI;

namespace MapRendering.Api {
	[UsedImplicitly]
	public class Map : AbsRestApi {

		protected override void HandleRestGet (RequestContext _context) {
			string id = _context.RequestPath;
			
			PrepareEnvelopedResult (out JsonWriter writer);

			switch (id) {
				case "config":
					writeConfig (ref writer);
					break;
				default:
					SendEmptyResponse (_context, HttpStatusCode.NotImplemented, _errorCode: "INVALID_ID");
					return;
			}
			
			SendEnvelopedResult (_context, ref writer);
		}

		private static readonly byte[] jsonKeyEnabled = JsonWriter.GetEncodedPropertyNameWithBeginObject ("enabled");
		private static readonly byte[] jsonKeyMapBlockSize = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("mapBlockSize");
		private static readonly byte[] jsonKeyMaxZoom = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("maxZoom");
		private static readonly byte[] jsonKeyMapSize = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("mapSize");
		
		private void writeConfig (ref JsonWriter writer) {
			writer.WriteRaw (jsonKeyEnabled);
			writer.WriteBoolean (MapRenderer.Enabled);

			writer.WriteRaw (jsonKeyMapBlockSize);
			writer.WriteInt32 (Constants.MapBlockSize);

			writer.WriteRaw (jsonKeyMaxZoom);
			writer.WriteInt32 (Constants.Zoomlevels - 1);

			GameManager.Instance.World.GetWorldExtent (out Vector3i worldMinPos, out Vector3i worldMaxPos);
			Vector3i worldSize = worldMaxPos - worldMinPos;

			writer.WriteRaw (jsonKeyMapSize);
			JsonCommons.WriteVector3I (ref writer, worldSize);
			
			writer.WriteEndObject ();
		}

		public override int[] DefaultMethodPermissionLevels () => new[] {
			AdminWebModules.MethodLevelNotSupported,
			AdminWebModules.PermissionLevelGuest,
			AdminWebModules.MethodLevelInheritGlobal,
			AdminWebModules.MethodLevelInheritGlobal,
			AdminWebModules.MethodLevelInheritGlobal
		};
	}
}