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

namespace AllocsFixes.NetConnections.Servers.Web.API
{
	public class GetPlayerInventory : WebAPI
	{
		public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)
		{
			if (req.QueryString ["steamid"] == null) {
				resp.StatusCode = (int)HttpStatusCode.InternalServerError;
				Web.SetResponseTextContent (resp, "No SteamID given");
				return;
			}

			Player p = PersistentContainer.Instance.Players [req.QueryString ["steamid"]];
			if (p == null) {
				resp.StatusCode = (int)HttpStatusCode.InternalServerError;
				Web.SetResponseTextContent (resp, "Invalid or unknown SteamID given");
				return;
			}

			PersistentData.Inventory inv = p.Inventory;


			JSONObject result = new JSONObject ();

			JSONArray bag = new JSONArray ();
			JSONArray belt = new JSONArray ();
			result.Add ("bag", bag);
			result.Add ("belt", belt);

			for (int i = 0; i < inv.belt.Count; i++) {
				JSONObject item = new JSONObject();
				if (inv.belt [i] != null) {
					item.Add ("count", new JSONNumber(inv.belt[i].count));
					item.Add ("name", new JSONString(inv.belt[i].itemName));
				} else {
					item.Add ("count", new JSONNumber(0));
					item.Add ("name", new JSONString(string.Empty));
				}
				belt.Add(item);
			}
			for (int i = 0; i < inv.bag.Count; i++) {
				JSONObject item = new JSONObject();
				if (inv.bag [i] != null) {
					item.Add ("count", new JSONNumber(inv.bag[i].count));
					item.Add ("name", new JSONString(inv.bag[i].itemName));
				} else {
					item.Add ("count", new JSONNumber(0));
					item.Add ("name", new JSONString(string.Empty));
				}
				bag.Add(item);
			}

			WriteJSON (resp, result);
		}
	}
}

