using AllocsFixes.JSON;
using AllocsFixes.PersistentData;
using System;
using System.Collections.Generic;
using System.Net;

namespace AllocsFixes.NetConnections.Servers.Web.API
{
	public class GetLandClaims : WebAPI
	{
		public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)
		{
			string steamid = string.Empty;

			if (req.QueryString ["steamid"] != null) {
				long tempLong;
				steamid = req.QueryString ["steamid"];
				if (steamid.Length != 17 || !long.TryParse (steamid, out tempLong)) {
					resp.StatusCode = (int)HttpStatusCode.InternalServerError;
					Web.SetResponseTextContent (resp, "Invalid SteamID given");
					return;
				}
			}

			JSONObject result = new JSONObject ();
			result.Add ("claimsize", new JSONNumber (GamePrefs.GetInt (EnumGamePrefs.LandClaimSize)));

			JSONArray claimOwners = new JSONArray ();
			result.Add ("claimowners", claimOwners);

			Dictionary<Vector3i, PersistentPlayerData> d = CommonMappingFunctions.GetGameManager ().GetPersistentPlayerList ().positionToLPBlockOwner;
			if (d != null) {
				World w = CommonMappingFunctions.GetGameManager ().World;
				Dictionary<PersistentPlayerData, List<Vector3i>> owners = new Dictionary<PersistentPlayerData, List<Vector3i>> ();
				foreach (KeyValuePair<Vector3i, PersistentPlayerData> kvp in d) {
					if (steamid.Length == 0 || kvp.Value.PlayerId.Equals (steamid)) {
						if (!owners.ContainsKey (kvp.Value)) {
							owners.Add (kvp.Value, new List<Vector3i> ());
						}
						owners [kvp.Value].Add (kvp.Key);
					}
				}

				foreach (KeyValuePair<PersistentPlayerData, List<Vector3i>> kvp in owners) {
					if (steamid.Length == 0 || kvp.Key.PlayerId.Equals (steamid)) {
						string curID = kvp.Key.PlayerId;
						bool isActive = w.LandClaimIsActive (kvp.Key);

						JSONObject owner = new JSONObject ();
						claimOwners.Add (owner);

						owner.Add ("steamid", new JSONString (curID));
						owner.Add ("claimactive", new JSONBoolean (isActive));

						JSONArray claims = new JSONArray ();
						owner.Add ("claims", claims);

						foreach (Vector3i v in kvp.Value) {
							JSONObject claim = new JSONObject ();
							claim.Add ("x", new JSONNumber (v.x));
							claim.Add ("y", new JSONNumber (v.y));
							claim.Add ("z", new JSONNumber (v.z));

							claims.Add (claim);
						}
					}
				}
			}

			WriteJSON (resp, result);
		}
	}
}

