package com.backfire.room.receiveDataManager;

import net.yeeyo.doudizhu.feiyu.R;
import android.os.Handler;

import com.backfire.Animation.AnimationClock;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.userinfo.UserInfo;
import com.backfire.doudizhu.userinfo.UserMessageCenter;
import com.backfire.room.RoomActivity;
import com.backfire.room.data.Player;
import com.backfire.room.data.ResCenter;
import com.backfire.room.data.RoomInfo;
import com.backfire.room.data.State.GameState;
import com.backfire.room.data.State.UserAction;
import com.backfire.room.data.State.UserState;
import com.backfire.socket.SocketCommand;
import com.backfire.socket.socketProto.Doudizhu.AuthRpy;
import com.backfire.socket.socketProto.Doudizhu.BroadcastLaiziCard;
import com.backfire.socket.socketProto.Doudizhu.BroadcastPlayerInfo;
import com.backfire.socket.socketProto.Doudizhu.PlayerPlayActionRpy;
import com.backfire.socket.socketProto.Doudizhu.RebindRpy;
import com.backfire.socket.socketProto.Doudizhu.SeatRpy;
import com.backfire.utils.Log;
import com.google.protobuf.InvalidProtocolBufferException;

public class UserProtoManager {
	RoomActivity mContext;
	AnimationClock animationClock = null;

	public UserProtoManager(RoomActivity mContext) {
		this.mContext = mContext;
	}

	/**
	 * 验证回应 optional uint32 ret = 1; //返回值，1成功，2失败 optional uint32 retCode = 2;
	 * //错误码 optional string retMsg = 3; //用户提示信息 实现功能： 1.成功 2.失败
	 */
	public void authRpy(byte[] data) {
		AuthRpy rpy = null;
		try {
			rpy = AuthRpy.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}

		if (null != rpy) {
			int ret = 2;
			if (rpy.hasRet()) {
				ret = rpy.getRet();
			}
			int retcode = 0;
			if (rpy.hasRetcode()) {
				retcode = rpy.getRetcode();
			}
			String retmsg = "";
			if (rpy.hasRetmsg()) {
				retmsg = rpy.getRetmsg();
			}
			Log.i(this, "ret:" + ret + "-->retcode:" + retcode + "---->retmsg:"
					+ retmsg);
			Log.i(this, "--------------------------------");
			if (ret == 1) { // 登陆成功
				// 发送坐下请求
				mContext.getRoom().getSocketSender().seatReq(1);
			} else {
				Log.e(rpy, "ret=" + ret + ",retCode=" + retcode + ",retmsg="
						+ retmsg);
				String msg = mContext.getString(R.string.network_error);
				mContext.showMessage(msg);
				mContext.toLobby();
			}
		} else {
			// 返回大厅：提示认证失败
			mContext.toLobby();
		}
	}

	public void playerActionRpy(byte[] data) {
		PlayerPlayActionRpy rpy = null;
		try {
			rpy = PlayerPlayActionRpy.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}

		if (null != rpy) {
			int ret = 2;
			if (rpy.hasRet()) {
				ret = rpy.getRet();
			}
			int retcode = 0;
			if (rpy.hasRetCode()) {
				retcode = rpy.getRetCode();
			}
			String retmsg = "";
			if (rpy.hasRetMsg()) {
				retmsg = rpy.getRetMsg();
			}
			if (SocketCommand.RET_SUCCESS == ret) {// 如果没有超时，继续操作
				RoomInfo roomInfo = RoomInfo.getInstance();
				Player player = roomInfo.getSelfPlayer();
				if (player != null) {
					synchronized (player) {
						int action = player.getAction();
						if (UserAction.PLAY == action) {
							// 操作成功
						} else if (UserAction.PASS == action) {
							player.setOperateAction(UserAction.PASS);
						}
					}
					// 更新上次选中的牌
					if (null != mContext.getRoom().getCardBtnManager()) {
						mContext.getRoom().getCardBtnManager()
								.unSelectAllCards();
					}
				}
			} else {// 超时，或其他错误
					// 1.出牌错误
					// 2.操作超时
					// 3.其他错误
				RoomInfo.getInstance().setSendReqing(false);
				RoomInfo.getInstance().getSelfPlayer()
						.setState(UserState.USER_PLAY_NEED);
			}
			Log.i(this, "ret:" + ret + "-->retcode:" + retcode + "---->retmsg:"
					+ retmsg);
			Log.i(this, "--------------------------------");
		}
	}

	/**
	 * 重新绑定回应 optional uint32 ret = 1; optional uint32 retcode = 2; optional
	 * string retmsg = 3; optional GameStart gamestart = 4; optional
	 * QiangdizhuRpy qdzRpy = 5; optional BroadcastPlayerAction playerAction =
	 * 6; optional BroadcastPlayerInfo playerinfo = 7; optional HandCard
	 * handcard = 8; optional uint32 seatid = 9; repeated uint32
	 * playerCardsRemain = 10; repeated PlayerDepositRpy deposited = 11;
	 * optional uint32 roomType = 12; repeated BroadcastLaiziCard laizi = 13;
	 * 
	 * @param data
	 */
	public void rebindRpy(byte[] data) {
		RebindRpy rpy = null;
		try {
			rpy = RebindRpy.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		if (rpy != null) {
			playerActionRpy(rpy);
		}
	}

	private void playerActionRpy(final RebindRpy rpy) {
		if (null != rpy && rpy.hasRet()
				&& rpy.getRet() == SocketCommand.RET_SUCCESS) {
			RoomInfo roomInfo = RoomInfo.getInstance();

			if (rpy.hasSeatid()) {
				int seatId = rpy.getSeatid();
				Log.i(this, "my seatid:" + seatId);
				// int cardNum=rpy.getPlayerCardsRemainCount();
				roomInfo.setSeatId(seatId);
				UserInfo userInfo = UserMessageCenter.getInstance()
						.getUserInfo();
				userInfo.setType(rpy.getRoomType());

				Player player = new Player();
				player.setSeatId(seatId);
				player.setUid(userInfo.getUid());
				player.setNick(userInfo.getNick());
				player.setIcon(ResCenter.getUserIcon(userInfo.getIcon()));
				player.setMoney(userInfo.getMoney());
				player.setLevel(userInfo.getLevel());
				player.setSex(userInfo.getSex());
				player.setSign(userInfo.getSignature());
				player.setLottery(userInfo.getLottery());
				// player.setCardNum(cardNum);

				// player.setItems(userInfo.getItems());

				player.setGameCount(userInfo.getGameCnt());
				player.setWinCount((int) userInfo.getWinCount());
				player.setDropCount(userInfo.getDropCnt());
				player.setRunCount(userInfo.getRunCnt());

				roomInfo.addPlayer(seatId, player);
			} else {
				Log.i(this, "RebindRpy missing seatid");
				return;
			}
			roomInfo.setRebinding(false); // 收到重连命令就代表着重连已经成功了
			roomInfo.setState(GameState.GAME_READY); // 代表游戏开始进入准备阶段

			if (rpy.hasSeatInfo()) {
				SeatRpy seatRpy = rpy.getSeatInfo();
				int basepoint = 0;
				if (seatRpy.hasBasepoint()) {
					basepoint = seatRpy.getBasepoint();
				}

				int readytimeout = 0;
				if (seatRpy.hasReadytimeout()) {
					readytimeout = seatRpy.getReadytimeout();
				}
				int awardRoom = 0;
				if (seatRpy.hasAwardRoom()) {
					awardRoom = seatRpy.getAwardRoom();
				}
				int laiziFlag = 0;
				if (seatRpy.hasLaiziFlag()) {
					laiziFlag = seatRpy.getLaiziFlag();
				}
				String roomName = "";
				if (seatRpy.hasRoomName()) {
					roomName = seatRpy.getRoomName();
				}
				Log.i(this, "---->basepoint:" + basepoint
						+ "---->readytimeout:" + readytimeout + ",awardRoom="
						+ awardRoom + ",laiziFlag=" + laiziFlag + ",roomName="
						+ roomName);
				roomInfo = RoomInfo.getInstance();
				roomInfo.setBasepoint(basepoint);
				roomInfo.setReadytimeout(readytimeout);
				roomInfo.setAwardRoom(awardRoom);
				roomInfo.setLaiziFlag(laiziFlag);
				roomInfo.setRoomName(roomName
						+ ResCenter.getFormSuffix(laiziFlag));
			}
			final BroadcastProtoManager broadcastProtoManager = mContext
					.getRoom().broadcastProtoManager;
			// 加载玩家信息
			if (rpy.hasPlayerinfo()) {
				BroadcastPlayerInfo broadcast = rpy.getPlayerinfo();
				broadcastProtoManager.playerInfoRpy(broadcast.toByteArray());
			} else {
				Log.i(this, "RebindRpy missing playerinfo");
				return;
			}

			// 手牌
			if (rpy.hasHandcard()) {
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						broadcastProtoManager.handCard(rpy.getHandcard()
								.toByteArray(), true);
					}

				}, 300);
			} else {
				Log.i(this, "RebindRpy missing handcard");
				return;
			}

			// 剩余牌数
			if (rpy.getPlayerCardsRemainCount() != 0) {
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						for (int i = 0; i < rpy.getPlayerCardsRemainCount(); ++i) {
							Player player = RoomInfo.getInstance().getPlayer(
									(i + 1) % 4);
							if (null != player) {
								synchronized (player) {
									player.setCardNum(rpy
											.getPlayerCardsRemain(i));
								}
								Log.i(this,
										"palyer seatid=" + (i + 1)
												+ ",cardsNum="
												+ rpy.getPlayerCardsRemain(i));
							}
						}
					}

				}, 400);
			} else {
				Log.i(this, "RebindRpy missing player cards remain");
				return;
			}

			// 癞子牌
			if (rpy.getLaiziCount() > 0) {
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						for (int i = 0; i < rpy.getLaiziCount(); ++i) {
							BroadcastLaiziCard laizi = rpy.getLaizi(i);
							broadcastProtoManager.addLaiZi(laizi.toByteArray(),
									true);
						}
					}

				}, 800);
			}

			// 设置托管
			if (rpy.getDepositedCount() > 0) {
				if (rpy.getLaiziCount() > 0) {
					(new Handler()).postDelayed(new Runnable() {

						@Override
						public void run() {
							for (int i = 0; i < rpy.getDepositedCount(); ++i) {
								broadcastProtoManager.depositRpy(rpy
										.getDeposited(i).toByteArray());
							}
						}

					}, 1000);
				}
			}

			if (rpy.hasGamestart()) {
				// 开始游戏回应
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						broadcastProtoManager.gameStart(rpy.getGamestart()
								.toByteArray(), true);
					}

				}, 1200);
			} else if (rpy.hasQdzRpy()) {
				// 抢地主回应
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						broadcastProtoManager.qiangDizhuRpy(rpy.getQdzRpy()
								.toByteArray());
					}

				}, 1200);
			} else {
				Log.i(this,
						"RebindRpy missing gamestart and qiangdizhu message");
				return;
			}

			if (rpy.hasPlayerAction()) {
				(new Handler()).postDelayed(new Runnable() {

					@Override
					public void run() {
						broadcastProtoManager.userAction(rpy.getPlayerAction()
								.toByteArray(), true);
					}

				}, 1600);
			}
		} else {
			// 失败
		}
	}
}
