package extend.mj.room.state;

import java.util.ArrayList;
import java.util.Collections;
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.core.entity.ITObject;
import com.taurus.core.entity.TObject;

import com.taurus.permanent.TPServer;
import extend.mj.*;
import extend.mj.player.state.EXPlayerPiaoNiaoTipState;

/**
 * ���䷢��״̬
 * 
 *
 * 2017��8��30��
 * EXRoomDealState.java
 */
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) {
			owner.bankerSeat = 1;
			ArrayList<Integer> randPlayer = new ArrayList<>();
			for (Entry<Integer, Player> entry : owner.playerMapBySeat.entrySet()) {
				Integer seat = entry.getKey();
				randPlayer.add(seat);
			}

			Collections.shuffle(randPlayer);
			if (randPlayer.size() > 0)
			{
				owner.bankerSeat = randPlayer.get(0);
			}
		}
		else {
			if (owner.config.getInt(Config.ROOM_CONFIG_XUAN_ZHUANG) == 0)
			{
				owner.bankerSeat = (owner.bankerSeat)%owner.maxPlayers+1;
			}
		}

		ITObject param = new TObject();
		param.putInt("bank_seat", owner.bankerSeat);
		EXMainServer.gameCtr.dealCard(owner);
		owner.playBackData = new EXPlayBack(owner);
		owner.stateMachine.changeState(Global.getState(EXRoomSetpState.class));
	}
}
