package card;

import server.InternalHanabiError;
import server.Message;

import java.util.ArrayList;
import java.util.List;

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

/*
 * COLORS:
 * GREEN
 * RED
 * YELLOW
 * WHITE
 * BLUE
 * (COLORED)
 */

public class Card {
	protected int color;
	protected int value;
	protected int id;
	protected List<CardInfo> cardInfos;
	protected boolean isSelected;

	public static Card DUMMY_CARD = new Card();
	static {
		DUMMY_CARD.color = -1;
		DUMMY_CARD.value = -1;
		DUMMY_CARD.id = -1;
		DUMMY_CARD.cardInfos = null;
	}

	public Card(int color, int value, int id) {
		this();
		this.color = color;
		this.value = value;
		this.id = id;
	}
	
	public Card() {
		cardInfos = new ArrayList<>();
	}

	public Card(Message m) {
		this();
		try {
			fromJson(m.getJson());
		} catch(JSONException ex) {
			throw new InternalHanabiError(ex);
		}
	}
	
	public void addCardInfo(int type, boolean is, int what, int from) {
		cardInfos.add(new CardInfo(type, is, what, from));
	}
	
	public List<CardInfo> getCardInfos() {
		return cardInfos;
	}
	
	public String colorToText() {
		return intColorToText(color);
	}
	
	public static String intColorToText(int id) {
		String color = "";
		switch(id){
		case 0:
			color = "green";
			break;
		case 1:
			color = "red";
			break;
		case 2:
			color = "yellow";
			break;
		case 3:
			color = "white";
			break;
		case 4:
			color = "blue";
			break;
		}
		return color;
	}
	
	public boolean isSelected() {
		return isSelected;
	}
	
	public void setSelected(boolean set) {
		isSelected = set;
	}
	
	public int getColorInt() {
		return color;
	}
	
	public int getValue() {
		return value;
	}
	
	public int getId() {
		return id;
	}

	public JSONObject toJson() throws JSONException {
		// TODO: handle dummy card
		JSONObject root = new JSONObject();
		root.put("value", value);
		root.put("id", id);
		root.put("color", color);
		root.put("cardInfos", cardInfosToJson());
		return root;
	}
	
	private JSONArray cardInfosToJson() throws JSONException {
		JSONArray infoArray = new JSONArray();
		if(cardInfos == null) return infoArray;
		for(CardInfo ci : cardInfos){
			infoArray.put(ci.toJson());
		}
		return infoArray;
	}
	
	private void fromJson(JSONObject jo) throws JSONException {
		// TODO: handle dummy card
		cardInfos = new ArrayList<>();
		int color = jo.getInt("color");
		int value = jo.getInt("value");
		int id = jo.getInt("id");
		JSONArray cardInfoArray = jo.getJSONArray("cardInfos");
		for(int i=0; i<cardInfoArray.length(); ++i){
			JSONObject cardInfo = cardInfoArray.getJSONObject(i);
			CardInfo ci = new CardInfo(new Message(cardInfo));
			cardInfos.add(ci);
		}
		this.color = color;
		this.value = value;
		this.id = id;
	}

	@Override
	public String toString(){
		return "[Color: " + color + "; Value: " + value + "; ID: " + id + "]";
	}
}
