package extend.mj.tip;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.game.Global;
import com.game.player.state.PlayerWaitState;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TArray;
import com.taurus.core.entity.TObject;

import extend.mj.EXPlayer;
import extend.mj.RuleWeight;

/**
 * 
 * 
 *
 *         2017��9��18�� TipManager.java
 */
public class TipManager {

	private int					id		= 0;

	public Map<Integer, Tip>	tipMap	= null;
	public Tip					actionTip;
	public int					weight	= 0;
	public EXPlayer				owner	= null;

	public TipManager(EXPlayer owner) {
		this.tipMap = new HashMap<Integer, Tip>();
		this.owner = owner;

	}

	public void addTip(Tip tip) {
		int id = this.getId();
		this.weight = this.weight | tip.weight;
		tip.id = id;
		this.tipMap.put(id, tip);
	}
	
	private void checkLouhu() {
		for (Entry<Integer, Tip> entry : this.tipMap.entrySet()) {
			Tip tip = entry.getValue();
			if(tip.type == RuleWeight.TYPE_WIN) {
				this.owner.louhu = true;
				break;
			}
		}
	}
	
	public void choicAction(int id) {
		if (id == 0) {
			this.checkLouhu();
			this.owner.stateMachine.changeState(Global.getState(PlayerWaitState.class));
			this.owner.getRoom().checkAction();
		} else if (this.tipMap.containsKey(id)) {
			Tip tip = this.tipMap.get(id);
			owner.stateMachine.changeState(Global.getState(PlayerWaitState.class));
			owner.getRoom().addAction(new Action(tip, owner));
		} else {
			throw new Error("tip map has no id" + id);
		}
	}

	@SuppressWarnings("unchecked")
	public void doAction(int id) {
		if (id == 0) {
			this.checkLouhu();
			this.owner.stateMachine.lastState.toNextState(owner);
		} else if (this.tipMap.containsKey(id)) {
			Tip tip = this.tipMap.get(id);
			owner.initOpCard(tip.opcard);
			tip.rule.action(owner,tip);

		} else {
			throw new Error("tip map has no id" + id);
		}

	}

	public ITObject toMP() {
		ITObject mp = new TObject();
		mp.putInt("weight", this.weight);
		ITArray tipList = new TArray();
		for (Entry<Integer, Tip> entry : this.tipMap.entrySet()) {
			Tip tip = entry.getValue();
			ITObject tipMp = tip.toMP();
			tipList.addTObject(tipMp);
		}
		mp.putTArray("tip_list", tipList);
		return mp;

	}

	private int getId() {
		this.id += 1;
		return this.id;
	}

	public int getWeightest() {
		int result = 0;
		for (Entry<Integer, Tip> entry : this.tipMap.entrySet()) {
			Tip tip = entry.getValue();
			if (tip.weight > result) {
				result = tip.weight;
			}
		}
		return result;
	}

	public void cleanTip() {
		this.weight = 0;
		this.id = 0;
		this.tipMap = new HashMap<Integer, Tip>();
	}

	public void clean() {
		this.cleanTip();
	}

}
