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.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);
		}
	}

	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);
	}

	@Override
	public void toNextState(EXRoom owner) {
		//洗牌
		owner.card.init();

		// 如果没有庄家，确定一个庄家
		if (owner.bankerSeat == 0) {
			if (owner.config.getBoolean(Config.ROOM_CONFIG_FIRST_RAND_ZHUANG))
			{
				owner.bankerSeat = getBankerSeat(owner);
			}
			else
			{
				owner.bankerSeat = 1;
			}
		}

		//发牌
		EXMainServer.gameCtr.dealCard(owner);

		// 去底牌
		if (owner.maxPlayers == 2 ) {
			int qupaiV = owner.config.getInt(Config.ROOM_CONFIG_QUPAI);
			if(qupaiV > 0) {

				int num = qupaiV * 5 + 5;
				for (int index = 0; index < num; index++) {
					owner.throwCardsList.add(owner.card.pop());
				}
			}
		}

		// 生成游戏记录对象
		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));
	}

	private int getBankerSeat(EXRoom owner) {
		int seat = 0;

		//如果是兩人的情況
		if (owner.maxPlayers == 2) {
			// 如果是随机确定庄家
			Random random = new Random();
			seat = random.nextInt(2) + 1;
		}
		else if (owner.maxPlayers == 3) {
			// 如果是随机确定庄家
				Random random = new Random();
				seat = random.nextInt(3) + 1;
		}
		else if (owner.maxPlayers == 4) {
			// 如果是随机确定庄家
			Random random = new Random();
			seat = random.nextInt(4) + 1;
		}
		return seat;
	}
}
