package extend.zp.room.state;

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.permanent.TPServer;
import extend.zp.Config;
import extend.zp.EXMainServer;
import extend.zp.EXPlayer;
import extend.zp.EXRoom;
import extend.zp.PlayBack;
import extend.zp.PlayerRuleManager;
import extend.zp.player.state.EXPlayerPreDrawState;


public class EXRoomDealState extends StateBase<EXRoom> {

	@Override
	public void enter(EXRoom owner) {
		boolean donghua = false;
		for (Entry<Integer, Player> entry : owner.playerMapById.entrySet()) {
			EXPlayer player = (EXPlayer) entry.getValue();
			if (player.xi_pai)
			{
				donghua = true;
				break;
			}
		}
		if (donghua)
		{
			owner.notifyXiPai();
			//启动定时器
			timer(owner);
		}
		else {

			this.toNextState(owner);
		}

		//this.toNextState(owner);
	}

	@Override
	public void toNextState(EXRoom owner) {
		owner.card.init();
		if (owner.bankerSeat == 0) {
			owner.bankerSeat = 1;
		}
		EXMainServer.gameCtr.dealCard(owner);
		//	Boolean qupaiV = owner.config.getBoolean(Config.ROOM_CONFIG_QUPAI);
		//	boolean qupai = (qupaiV == null) ? false : qupaiV;
		int qupaiV = owner.config.getInt(Config.ROOM_CONFIG_QUPAI);
		if (owner.maxPlayers == 2 && qupaiV>0) {
			for (int index = 0; index < 20; index++) {
				owner.throwCardsList.add(owner.card.pop());
			}
		}
		// owner.isplaying = true;
		// owner.round += 1;
		owner.playBackData = new PlayBack(owner);
		for (Entry<Integer, Player> entry : owner.playerMapById.entrySet()) {
			EXPlayer player = (EXPlayer) entry.getValue();
			if (player.seat != owner.bankerSeat) {
				EXMainServer.playerRuleMgr.conditionEx(PlayerRuleManager.DEAL_RULE, player);
			}
		}
		EXPlayer player = (EXPlayer) owner.playerMapBySeat.get(owner.bankerSeat);
		EXMainServer.gameCtr.changeActiveSeat(owner, player.seat);
		player.stateMachine.changeState(Global.getState(EXPlayerPreDrawState.class));
	}

	public static void timer(EXRoom owner) {

		TPServer.me().getTimerPool().schedule(new Runnable() {

			@Override
			public void run() {

				if (owner == null) {
					Global.logger.error("room is null");
					return;
				}

				if (owner.isDestroy)
					return;

				owner.enqueueRunnable(new Runnable() {
					@Override
					public void run() {
						owner.stateMachine.toNextState();
					}
				});
			}
		}, 4000, TimeUnit.MILLISECONDS);
	}

}
