package extend.pk.room.state;



import com.game.Global;
import com.game.data.Player;
import com.game.state.StateBase;

import com.taurus.permanent.TPServer;
import extend.pk.Config;
import extend.pk.EXMainServer;
import extend.pk.EXPlayBack;
import extend.pk.EXPlayer;
import extend.pk.EXRoom;
import extend.pk.uitl.CardCheck;

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

/**
 * 房间发牌状态
 * 
 * 
 */
public class EXRoomDealState extends StateBase<EXRoom> {
	@Override
	public void enter(EXRoom owner) {
		boolean donghua = false;
		for (Map.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);
		}

	}

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

	@Override
	public void toNextState(EXRoom owner) {
		//owner.card.init();
		if(owner.bankerSeat!=0&&!owner.playerMapBySeat.containsKey(owner.bankerSeat)) {
			owner.bankerSeat = 0;
		}
		EXMainServer.gameCtr.dealCard(owner);

		owner.playBackData = new EXPlayBack(owner);
		
		if(owner.config.getInt(Config.ROOM_CONFIG_MINBOOM) == 1) {
			
			int startSpringSeat = 0;
			int seat = owner.bankerSeat;
			do {
				
				EXPlayer player = (EXPlayer)owner.playerMapBySeat.get(seat);
				if(CardCheck.checkStartSpring(player.cardInhand)) {
					
					startSpringSeat = seat;
					break;
				}	
			}while(seat != owner.bankerSeat);
			
			if(startSpringSeat != 0) {
				owner.bankerSeat = startSpringSeat;
				owner.win = (EXPlayer)owner.playerMapBySeat.get(startSpringSeat);
				owner.endGame();
				return;
			}
		}	
			
		
		
		owner.stateMachine.changeState(Global.getState(EXRoomSetpState.class));
	}
}
