package extend.mj.player.state;

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

import com.game.Global;
import com.game.player.state.PlayerPauseState;
import com.game.player.state.PlayerWaitState;
import com.game.state.StateBase;

import com.taurus.permanent.TPServer;
import extend.mj.*;
import extend.mj.room.state.EXRoomSetpState;
import extend.mj.tip.TipManager;

/**
 * 
 */
public class EXPlayerOpenKongState extends StateBase<EXPlayer> {

	@Override
	public void enter(EXPlayer owner) {
		owner.louhu = false;
		owner.autoOutCard = true;
		
		EXRoom room = owner.getRoom();
		OpenKong ok = room.activeKong;
		if (ok != null) {
			ok.drawList.add(room.card.pop());
			if (room.card.getCount() > 0)
				ok.drawList.add(room.card.pop());
			if (room.config.getInt(Config.ROOM_CONFIG_KAI_GONG) > 0)
			{
				if (room.card.getCount() > 0)
					ok.drawList.add(room.card.pop());
				if (room.card.getCount() > 0)
					ok.drawList.add(room.card.pop());
			}
			if(room.card.getCount() == 0){
				ok.haidi = true;
			}
		}
		
		for(Integer card : ok.drawList) {
			owner.outcardList.add(card);
		}

		int leftCount = room.card.getCount();
		((EXGameController)Global.gameCtr).openKongEvent(owner, leftCount, ok);

		timer(owner.getRoom(), owner, this);
	}

	public static void timer(EXRoom room, EXPlayer owner, EXPlayerOpenKongState state) {

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

			@Override
			public void run() {

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

				if (room.isDestroy)
					return;

				room.enqueueRunnable(new Runnable() {

					@Override
					public void run() {
						room.broadCastToServer(owner.playerid, EXActionEvent.EVENT_OPENKONG, null);
						int win_count = 0;
						for (Entry<Integer, TipManager> entry : room.tipMap.entrySet()) {
							TipManager tipmgr = entry.getValue();
							if(tipmgr.isWin)win_count++;
						}
						room.tongpao = 0;
						if( win_count>1)room.tongpao = win_count;

						EXMainServer.playerRuleMgr.condition(PlayerRuleManager.OPENKONG_RULE, owner,false);
						if (room.tipMap.size() == 0) {
							room.activeKong = null;
							state.toNextState(owner);
						}
					}
				});
			}
		}, 4000, TimeUnit.MILLISECONDS);
	}

	@Override
	public void toNextState(EXPlayer owner) {
		if(owner.getRoom().activeKong == null) {
			owner.stateMachine.changeState(Global.getState(PlayerWaitState.class));
			owner.room.stateMachine.changeState(Global.getState(EXRoomSetpState.class));
		}else {
			
			owner.stateMachine.changeState(Global.getState(PlayerPauseState.class));
		}
		
	}


}
