package extend.zp.room.state;

import java.util.Map.Entry;
import java.util.Random;
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.*;
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;
			//随机定庄
			Random random = new Random();
			owner.bankerSeat = random.nextInt(2) + 1;
		}
		EXMainServer.gameCtr.dealCard(owner);
		//System.out.println("isdianpao:"+owner.isFanPao);


		//if (owner.playBackData==null){
			owner.playBackData = new PlayBack(owner);
			//发起返佣开始
			owner.endsendflag = false;

		//}

		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();
					}
				});
			}
		}, 500, TimeUnit.MILLISECONDS);
	}

}
