package com.backfire.room.manager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;

import android.view.MotionEvent;

import com.backfire.arithmetic.Card;
import com.backfire.arithmetic.CardAssist;
import com.backfire.arithmetic.CardAuto3;
import com.backfire.arithmetic.CardAuto3_Laizi;
import com.backfire.arithmetic.CardCompare.CompareValue;
import com.backfire.arithmetic.CardCompare3;
import com.backfire.arithmetic.CardCompare3_Laizi;
import com.backfire.arithmetic.CardJudge.CardType;
import com.backfire.arithmetic.CardJudge3;
import com.backfire.arithmetic.CardJudge3_Laizi;
import com.backfire.arithmetic.CardJudge3_Laizi.CardType_Laizi;
import com.backfire.arithmetic.CardReturn;
import com.backfire.arithmetic.CardReturn_Laizi;
import com.backfire.graphics.PCanvas;
import com.backfire.room.Room;
import com.backfire.room.Interface.IClickListener;
import com.backfire.room.data.HandlerMsg;
import com.backfire.room.data.Player;
import com.backfire.room.data.RoomInfo;
import com.backfire.room.data.RoomInfo.GameType;
import com.backfire.room.data.State.UserState;
import com.backfire.widget.RoomButton;

/**
 * @Title: GameControlBtnManager.java
 * @Description: 用户玩牌控制管理类
 * @author Potter
 * @date 2013年10月24日 上午11:09:49
 * @version V2.0
 */
public class GameControlBtnManager {
	public Map<Integer, RoomButton> btnMap = null;
	public ArrayList<ArrayList<Card>> mPromptCards;
	public int curPromptIndex = 0;

	//public IUpdateCard iUpdateCard = null;

	public IClickListener iClickListener = null;
	public Room mRoom;
	public GameControlBtnManager(Room mRoom,Map<Integer, RoomButton> btnMap,
			IClickListener iClickListener) {
		this.mRoom = mRoom;
		this.btnMap = btnMap;
		this.iClickListener = iClickListener;
		mPromptCards = new ArrayList<ArrayList<Card>>();

	}

	public void draw(PCanvas canvas) {
		for (Entry<Integer, RoomButton> entry : btnMap.entrySet()) {
			RoomButton button=entry.getValue();
			if(button!=null){
				synchronized (button) {
					button.initDraw();
				}
			}
			button.draw(canvas);
		}
	}

	public boolean touch(MotionEvent event) {
		boolean result = false;
		int key = 0;
		for (Entry<Integer, RoomButton> entry : btnMap.entrySet()) {
			key = entry.getKey();
			RoomButton roomButton = entry.getValue();
			if(roomButton!=null){
				synchronized (roomButton) {
					result = roomButton.dispatch(event);
				}
			}
			if (!result)continue;
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if (HandlerMsg.MSG_RE_SELECT == key) {
					if (null != mRoom && mRoom.getCardBtnManager()!=null) {
						if (null != mPromptCards && !mPromptCards.isEmpty()) {
							curPromptIndex = mPromptCards.size() - 1;
						} else {
							curPromptIndex = 0;
						}
						mRoom.getCardBtnManager().unSelectAllCards();
						updateBtn(HandlerMsg.MSG_PLAY, true, false);
					}
				} else if (HandlerMsg.MSG_PROMPT == key) {
					onTouchPrompt();
				} else if (HandlerMsg.MSG_PASS == key) {
					if (null != mRoom && mRoom.getCardBtnManager()!=null) {
						mRoom.getCardBtnManager().unSelectAllCards();
					}
				}
			}
			break;
		}
		return result;
	}

	private void onTouchPrompt() {
		// 提示牌为0表示没有大的过的牌
		// 直接不出
		if (0 == mPromptCards.size()) {
			iClickListener.sendMsg(HandlerMsg.MSG_PASS);
			return;
		}

		ArrayList<Card> selected = new ArrayList<Card>();
		if (null != mRoom && mRoom.getCardBtnManager()!=null) {
			selected = mRoom.getCardBtnManager().getSelectCards();
		}

		// 跳过重复的提示
		if (curPromptIndex >= 0 && curPromptIndex < mPromptCards.size()) {
			if (isSameType(mPromptCards.get(curPromptIndex), selected)) {// 说明要跳过此提示
				offsetPromptIdx();
			}
		} else {
			return;
		}
		
		// 重置牌，然后选取提示牌
		if (null != mRoom && mRoom.getCardBtnManager()!=null) {
			mRoom.getCardBtnManager().unSelectAllCards();
			mRoom.getCardBtnManager().selectCards(mPromptCards.get(curPromptIndex));
			// 出牌显示
			updateBtn(HandlerMsg.MSG_PLAY, true, true);
		}
	}
	
	/**
	 * 偏移提示idx值
	 */
	public void offsetPromptIdx() {
		curPromptIndex++;
		if (curPromptIndex >= mPromptCards.size()) {
			curPromptIndex = 0;
		}
	}

	private boolean isSameType(final ArrayList<Card> cards1,
			final ArrayList<Card> cards2) {
		if (cards1.size() != cards2.size())
			return false;

		ArrayList<Card> card1Sorted = CardAssist.copyList(cards1);
		ArrayList<Card> card2Sorted = CardAssist.copyList(cards2);
		Collections.sort(cards1, new CardAssist.Desc());
		Collections.sort(cards2, new CardAssist.Desc());

		for (int i = 0; i < card1Sorted.size(); ++i) {
			if (!card1Sorted.get(i).isSamePoint(card2Sorted.get(i)))
				return false;
		}
		return true;
	}

	public void updateBtn(int msg, boolean isVisible, boolean enable) {
		if (null == btnMap)
			return;
		RoomButton button = btnMap.get(msg);
		if (null != button) {
			synchronized (button) {
				button.setVisible(isVisible);
				button.setEnable(enable);
			}
		}
	}

	public void updateGameControlBtnState(ArrayList<Card> selectCards) {
		RoomButton roomButton = btnMap.get(HandlerMsg.MSG_PLAY);
		boolean playEnable = false;// play能否可按
		if (null == roomButton)
			return;
		if (null == selectCards || selectCards.isEmpty()) {
			synchronized (roomButton) {
				roomButton.setEnable(playEnable);
			}
		}
		// 添加算法
		RoomInfo roomInfo = RoomInfo.getInstance();
		boolean isLaiziMode = roomInfo.isLaiziType();
		ArrayList<Card> lastOutCards = roomInfo.getLastOutCards();

		do {
			if (isLaiziMode) {
				CardJudge3_Laizi judge = new CardJudge3_Laizi();
				CardReturn_Laizi result = judge.judgeCardType(selectCards);
				if (result.mCardType == CardType_Laizi.CardEnd
						|| result.mCardType == CardType_Laizi.NONE)
					break;
			} else {
				// 牌型是否有效
				CardJudge3 judge = new CardJudge3();
				CardReturn judgeRet = judge.judgeCardType(selectCards);
				if (judgeRet.mCardType == CardType.CardEnd)
					break;
			}

			// 比较和上家出牌的大小
			if (lastOutCards.size() > 0) {
				int result = 0;
				if (isLaiziMode) {
					CardCompare3_Laizi compare = new CardCompare3_Laizi();
					result = compare.compareCard(selectCards, lastOutCards);
					if (result != CompareValue.MoreThan)
						break;
				} else {
					CardCompare3 compare = new CardCompare3();
					result = compare.compareCard(selectCards, lastOutCards);
					if (result != CompareValue.MoreThan)
						break;
				}
			}

			// 验证通过可以出牌
			playEnable = true;
		} while (false);
		synchronized (roomButton) {
			roomButton.setEnable(playEnable);
		}
	}

	public void updatePromptSelectCards() {
		ArrayList<Card> handCards = RoomInfo.getInstance().getMyCards();
		GameType gameType = RoomInfo.getInstance().getGameType();
		boolean isLaiziType = RoomInfo.getInstance().isLaiziType();
		if (isLaiziType) {
			CardJudge3_Laizi judge = new CardJudge3_Laizi();
			CardType_Laizi result = judge.judgeCardType(handCards).mCardType;
			if (result == CardType_Laizi.PLANE
					|| result == CardType_Laizi.PLANE_1
					|| result == CardType_Laizi.PLANE_2
					|| result == CardType_Laizi.FOUR_WITH_X) {
				return;
			}
		} else {
			CardJudge3 judge = new CardJudge3();
			CardType judgeRet = judge.judgeCardType(handCards).mCardType;
			if (judgeRet == CardType.CardFourWithTwo || // 四带二
					judgeRet == CardType.CardFourWithTwoPair || // 四带两对
					judgeRet == CardType.CardAirplaneOne || // 飞机三带一
					judgeRet == CardType.CardAirplaneTwo) // 飞机三带二
			{
				return;
			}
		}

		// 若新选的牌在牌组中,选中提示牌 反选其他牌
		if (GameType.LAIZI != gameType) {

		}
	}

	public void updatePlayPrompt() {
		RoomInfo roomInfo = RoomInfo.getInstance();
		ArrayList<Card> handCards = CardAssist.copyList(roomInfo.getMyCards());
		ArrayList<Card> lastOutCards = CardAssist.copyList(roomInfo
				.getLastOutCards());
		boolean isLaizi = roomInfo.isLaiziType();

		if (isLaizi) {
			CardAuto3_Laizi cardAuto3_Laizi = new CardAuto3_Laizi();
			mPromptCards = cardAuto3_Laizi.judgeCanBe(handCards, lastOutCards);
		} else {
			CardAuto3 cardPrompt = new CardAuto3();
			mPromptCards = cardPrompt.judgeCanBe(handCards, lastOutCards);
		}
		curPromptIndex = 0;

		// 没有大的过的牌
		if (mPromptCards.size() == 0) {
			RoomButton roomButton = btnMap.get(HandlerMsg.MSG_PROMPT);
			if (null != roomButton) {
				roomButton.setEnable(false);
			}
		}
	}

	public void updateBtnState() {
		int lastSeatId = RoomInfo.getInstance().getLastOutCardSeatId();
		boolean isSendReqing = RoomInfo.getInstance().isSendReqing();
		boolean isRefight = RoomInfo.getInstance().isRefight();
		Player player = RoomInfo.getInstance().getSelfPlayer();
		if (null == player)
			return;
		int state = 0;
		int seatId = 0;
		boolean isDesposit = false;
		synchronized (player) {
			state = player.getState();
			isDesposit = player.isDeposit();
			seatId = player.getSeatId();
		}
		ArrayList<Integer> keys = new ArrayList<Integer>();
		if (!isSendReqing) {
			switch (state) {
			case UserState.USER_READY_NEED:
				if (isRefight) {
					keys.add(HandlerMsg.MSG_READY);
					keys.add(HandlerMsg.MSG_LEAVE);
				}else{
					iClickListener.sendMsg(HandlerMsg.MSG_READY);
				}
				break;
			case UserState.USER_READY:
				//keys.add(HandlerMsg.MSG_CENTER_LEAVE);
				break;
			case UserState.USER_CALL_NEED:
				keys.add(HandlerMsg.MSG_ONE);
				keys.add(HandlerMsg.MSG_TWO);
				keys.add(HandlerMsg.MSG_THREE);
				break;
			case UserState.USER_GRAB_NEED:
				keys.add(HandlerMsg.MSG_GRAB);
				keys.add(HandlerMsg.MSG_NO_GRAB);
				break;
			case UserState.USER_PLAY_NEED:
				if (!isDesposit) {
					keys.add(HandlerMsg.MSG_PASS);
					keys.add(HandlerMsg.MSG_RE_SELECT);
					keys.add(HandlerMsg.MSG_PROMPT);
					keys.add(HandlerMsg.MSG_PLAY);
				}
				break;
			}
		}
		if (isDesposit) {
			keys.add(HandlerMsg.MSG_CANCEL_DESPOSITE);
		}
		for (Entry<Integer, RoomButton> entry : btnMap.entrySet()) {
			int key = entry.getKey();
			RoomButton button = entry.getValue();
			if (keys.contains(key)) {
				if ((seatId == lastSeatId || 0 == lastSeatId)
						&& (HandlerMsg.MSG_PASS == key || HandlerMsg.MSG_PROMPT == key)) {
					button.setEnable(false);
				} else {
					// 出牌能不能点不由他控制
					if (HandlerMsg.MSG_PLAY != key) {
						button.setEnable(true);
					}
				}
				button.setVisible(true);
			} else {
				button.setEnable(false);
				button.setVisible(false);
			}
		}
	}

	public void reset() {
		if (null == btnMap)
			return;
		synchronized (btnMap) {
			for (Entry<Integer, RoomButton> entry : btnMap.entrySet()) {
				RoomButton roomButton = entry.getValue();
				roomButton.setVisible(false);
				roomButton.setEnable(false);
			}
		}
	}
	public void clear() {
		if(btnMap!=null){
			synchronized (btnMap) {
				for(Entry<Integer, RoomButton> entry:btnMap.entrySet()){
					RoomButton button=entry.getValue();
					if(button!=null){
						synchronized (button) {
							button.clear();
						}
						button = null;
					}
				}
			}
			btnMap.clear();
			btnMap = null;
		}
	}
}