package extend.zp.player.state;

import java.util.Collections;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import com.game.Global;
import com.game.data.Player;
import com.game.state.StateBase;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TObject;
import com.taurus.permanent.TPServer;

import extend.zp.Config;
import extend.zp.EXActionEvent;
import extend.zp.EXMainServer;
import extend.zp.EXPlayer;
import extend.zp.EXRoom;
import extend.zp.PlayerRuleManager;
import extend.zp.uitl.CardUtil;


public class EXPlayerPreDrawState extends StateBase<EXPlayer> {
	@Override
	public void enter(EXPlayer owner) {
		EXRoom room = owner.getRoom();
		room.isAllPass = false;
		int card = room.card.pop();
		//card = 104;
		room.isAllPass = false;
		int leftCount = room.card.getCount();

		owner.cardInhand.add(card);
		Collections.sort(owner.cardInhand);

		ITObject param = new TObject();
		param.putInt("left_count", leftCount);
		param.putInt("card", card);
		param.putInt("seat", owner.room.activeSeat);
		owner.sendEvent(Config.GAME_EVT_ADDDRAW, param);
		CardUtil.sendSuoCardEvent(owner);
		room.getPlayBack().addAddCardCommand(owner.room.activeSeat, card, leftCount);
		ITObject param1 = new TObject();
		param1.putInt("left_count", leftCount);
		param1.putInt("card", 0);
		param1.putInt("seat", owner.room.activeSeat);
		room.broadCastToClient(owner.playerid, Config.GAME_EVT_ADDDRAW, param1);
		room.draw = owner.seat;
		for (Entry<Integer, Player> entry : room.playerMapBySeat.entrySet()) {
			if (entry.getKey() != owner.seat) {
				EXPlayer player = (EXPlayer) entry.getValue();
				EXMainServer.gameCtr.qiShouTing(player);
			}
		}
		//EXMainServer.playerRuleMgr.condition(PlayerRuleManager.WIN_RULE, owner);
		timer(owner);
	}

	@Override
	public void toNextState(EXPlayer owner) {
		owner.getRoom().tianHu = false;
		owner.stateMachine.changeState(Global.getState(EXPlayerDiscardState.class));
	}
	
	public void timer(EXPlayer owner) {
		TPServer.me().getTimerPool().schedule(new Runnable() {
			@Override
			public void run() {
				if (owner.room == null) {
					Global.logger.error("EXPlayerDiscardState room is null");
					return;
				}
				if (owner.room.isDestroy)
					return;
				owner.room.enqueueRunnable(new Runnable() {
					@Override
					public void run() {
						EXMainServer.playerRuleMgr.conditionEx(PlayerRuleManager.WIN_RULE, owner);
						owner.room.broadCastToServer(owner.playerid, EXActionEvent.EVENT_WIN, null);
						if (owner.getRoom().tipMap.size() == 0) {
							toNextState(owner);
						}
					}
				});
			}
		}, 300, TimeUnit.MILLISECONDS);
	}
}
