using System.Collections.Generic;
using JetBrains.Annotations;
using Utf8Json;
using Webserver.LiveData;

namespace Webserver.WebAPI.APIs.WorldState {
	[UsedImplicitly]
	internal class Animal : AbsRestApi {
		private readonly List<EntityAnimal> entities = new List<EntityAnimal> ();

		private static readonly byte[] jsonKeyId = JsonWriter.GetEncodedPropertyNameWithBeginObject ("id");
		private static readonly byte[] jsonKeyName = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("name");
		private static readonly byte[] jsonKeyPosition = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("position");

		protected override void HandleRestGet (RequestContext _context) {
			PrepareEnvelopedResult (out JsonWriter writer);
			writer.WriteBeginArray ();
			
			lock (entities) {
				Animals.Instance.Get (entities);
				
				for (int i = 0; i < entities.Count; i++) {
					if (i > 0) {
						writer.WriteValueSeparator ();
					}
					
					EntityAlive entity = entities [i];
					Vector3i position = new Vector3i (entity.GetPosition ());
					
					writer.WriteRaw (jsonKeyId);
					writer.WriteInt32 (entity.entityId);
					
					writer.WriteRaw (jsonKeyName);
					writer.WriteString (!string.IsNullOrEmpty (entity.EntityName) ? entity.EntityName : $"animal class #{entity.entityClass}");
					
					writer.WriteRaw (jsonKeyPosition);
					JsonCommons.WriteVector3I (ref writer, position);

					writer.WriteEndObject ();
				}
			}
			
			writer.WriteEndArray ();
			SendEnvelopedResult (_context, ref writer);
		}
	}
}