package player;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import card.Card;
import server.InternalHanabiError;
import server.Move;

public class BasePlayer {
	protected int id;
	protected String name;
	protected Card[] cards;

	public BasePlayer(int id, int nrOfCards) {
		this(id, nrOfCards, "Player " + id);
	}
	
	public BasePlayer(int id, int nrOfCards, String name) {
		this();
		this.id = id;
		this.cards = new Card[nrOfCards];
		this.name = name;
	}
	
	public BasePlayer(Move m) {
		this();
		try {
			fromJson(m.getJson());
		} catch(JSONException ex){
			throw new InternalHanabiError(ex);
		}
	}
	
	private BasePlayer() { }

	public void setCards(JSONArray ja) {
		cards = new Card[ja.length()];
		for(int i=0; i<ja.length(); ++i) {
			JSONObject jsonCard = null;
			Card card = null;
			try {
				jsonCard = ja.getJSONObject(i);
				card = new Card(new Move(jsonCard));
			} catch(JSONException ex) {
				throw new InternalHanabiError(ex);
			}
			cards[i] = card;
		}
	}

	public void setCard(int index, Card c) {
		cards[index] = c;
	}
	
	public Card getCard(int index) {
		return cards[index];
	}

	public Card[] getCards() {
		return cards;
	}

	public String getName() {
		return name;
	}

	public JSONObject toJson() throws JSONException {
		JSONObject root = new JSONObject();
		root.put("name", name);
		root.put("id",  id);
		root.put("cards", cardsToJson());
		return root;
	}
	
	private JSONArray cardsToJson() throws JSONException {
		JSONArray cardArray = new JSONArray();
		for(Card c : cards) {
			cardArray.put(c.toJson());
		}
		return cardArray;
	}
	
	private void fromJson(JSONObject jo) throws JSONException {
		int id = jo.getInt("id");
		String name = jo.getString("name");
		setCards(jo.getJSONArray("cards"));
		this.id = id;
		this.name = name;
	}
}
