using System;
using UnityEngine;
using Utf8Json;

namespace Webserver.WebAPI {
	public static class JsonCommons {
		private static readonly byte[] jsonKeyPositionX = JsonWriter.GetEncodedPropertyNameWithBeginObject ("x");
		private static readonly byte[] jsonKeyPositionY = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("y");
		private static readonly byte[] jsonKeyPositionZ = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("z");

		public static void WritePositionObject (ref JsonWriter _writer, Vector3i _position) {
			_writer.WriteRaw (jsonKeyPositionX);
			_writer.WriteInt32 (_position.x);
			
			_writer.WriteRaw (jsonKeyPositionY);
			_writer.WriteInt32 (_position.y);
			
			_writer.WriteRaw (jsonKeyPositionZ);
			_writer.WriteInt32 (_position.z);
			
			_writer.WriteEndObject ();
		}

		public static void WritePositionObject (ref JsonWriter _writer, Vector3 _position) {
			_writer.WriteRaw (jsonKeyPositionX);
			_writer.WriteSingle (_position.x);
			
			_writer.WriteRaw (jsonKeyPositionY);
			_writer.WriteSingle (_position.y);
			
			_writer.WriteRaw (jsonKeyPositionZ);
			_writer.WriteSingle (_position.z);
			
			_writer.WriteEndObject ();
		}

		private static readonly byte[] jsonKeyCombinedString = JsonWriter.GetEncodedPropertyNameWithBeginObject ("combinedString");
		private static readonly byte[] jsonKeyPlatformId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("platformId");
		private static readonly byte[] jsonKeyUserId = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("userId");

		public static void WritePlatformUserIdentifier (ref JsonWriter _writer, PlatformUserIdentifierAbs _userIdentifier) {
			if (_userIdentifier == null) {
				_writer.WriteNull ();
				return;
			}
			
			_writer.WriteRaw (jsonKeyCombinedString);
			_writer.WriteString (_userIdentifier.CombinedString);
			
			_writer.WriteRaw (jsonKeyPlatformId);
			_writer.WriteString (_userIdentifier.PlatformIdentifierString);
			
			_writer.WriteRaw (jsonKeyUserId);
			_writer.WriteString (_userIdentifier.ReadablePlatformUserIdentifier);
			
			_writer.WriteEndObject ();
		}

		public static void WriteDateTime (ref JsonWriter _writer, DateTime _dateTime) {
			_writer.WriteString (_dateTime.ToString ("o"));
		}

		public static void WriteStringOrNull (ref JsonWriter _writer, string _string) {
			if (_string == null) {
				_writer.WriteNull ();
			} else {
				_writer.WriteString (_string);
			}
		}
	}
}