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

namespace AllocsFixes.NetConnections.Servers.Web.API
{
	public class GetPlayersOnline : WebAPI
	{
		public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)
		{
			JSONArray players = new JSONArray();

			World w = CommonMappingFunctions.GetGameManager ().World;
			foreach (KeyValuePair<int, EntityPlayer> current in w.Players.dict) {
				ClientInfo ci = CommonMappingFunctions.GetClientInfoFromEntityID (current.Key);
				string ip = string.Empty;
				if (ci != null) {
					ip = ci.networkPlayer.ipAddress;
				}

				JSONObject pos = new JSONObject();
				pos.Add("x", new JSONNumber((int)current.Value.GetPosition().x));
				pos.Add("y", new JSONNumber((int)current.Value.GetPosition().y));
				pos.Add("z", new JSONNumber((int)current.Value.GetPosition().z));

				JSONObject p = new JSONObject();
				p.Add("steamid", new JSONString(CommonMappingFunctions.GetSteamID (ci)));
				p.Add("ip", new JSONString(ip));
				p.Add("name", new JSONString(current.Value.EntityName));
				p.Add("online", new JSONBoolean(true));
				p.Add("position", pos);

				players.Add(p);
			}

			WriteJSON(resp, players);
		}
	}
}

