package player;

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

import card.Card;
import server.ServerGame.PROTOCOL;

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

	public BasePlayer(int id, int nrOfCards){
		this(id, nrOfCards, "");
	}
	
	public BasePlayer(int id, int nrOfCards, String name){
		this();
		this.id = id;
		this.cards = new Card[nrOfCards];
		this.name = name;
	}
	
	public BasePlayer(JSONObject jo){
		this();
		cards = new Card[jo.getJSONArray("cards").length()];
		fromJson(jo);
	}
	
	private BasePlayer() {
		PROTO = PROTOCOL.VIBE_DUMB;
	}
	
	public void setCard(int index, Card c){
		cards[index] = c;
	}
	
	public Card getCard(int index){
		return cards[index];
	}
	
	public Card[] getCards(){
		return cards;
	}
	
	public JSONObject toJson(){
		JSONObject root = new JSONObject();
		root.put("name", name);
		root.put("id",  id);
		root.put("cards", cardsToJson());
		return root;
	}
	
	private JSONArray cardsToJson(){
		JSONArray cardArray = new JSONArray();
		for(Card c : cards){
			cardArray.put(c.toJson());
		}
		return cardArray;
	}
	
	private void fromJson(JSONObject jo){
		int id = jo.getInt("id");
		String name = jo.getString("name");
		JSONArray cardsArray = jo.getJSONArray("cards");
		for(int i=0; i<cardsArray.length(); ++i){
			JSONObject card = cardsArray.getJSONObject(i);
			Card c = new Card(card);
			cards[i] = c;
		}
		this.id = id;
		this.name = name;
	}
}
