package com.backfire.room;

import java.util.HashMap;
import java.util.TreeMap;

import net.yeeyo.doudizhu.feiyu.R;

import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;

//import cn.wimipay.sdk.WimiPaySdk;

import com.backfire.Animation.AnimationChatToast;
import com.backfire.Animation.AnimationClock;
import com.backfire.Animation.AnimationManager;
import com.backfire.doudizhu.ActivityContainer;
import com.backfire.doudizhu.ActivityThirdPlatform;
import com.backfire.doudizhu.common.ClickFilter;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.common.JSONUtil;
import com.backfire.doudizhu.common.LoadingProgressDialog;
import com.backfire.doudizhu.common.MyJson;
import com.backfire.doudizhu.common.ShareData;
import com.backfire.doudizhu.common.WakeLock;
import com.backfire.doudizhu.lobby.AddStatistics;
import com.backfire.doudizhu.userinfo.UserInfo;
import com.backfire.doudizhu.userinfo.UserMessageCenter;
import com.backfire.php.PHPCallbackInterface;
import com.backfire.php.PHPMethodName;
import com.backfire.php.PHPRequestPool;
import com.backfire.php.PHPResult;
import com.backfire.php.PHPResult.ErrorCode;
import com.backfire.popupwindow.AlertPopupWindow;
import com.backfire.popupwindow.ChatPopupWindow;
import com.backfire.popupwindow.OtherInfoPop;
import com.backfire.popupwindow.SelectPopupWindow;
import com.backfire.popupwindow.SettingPopUpWindow;
import com.backfire.room.data.ConfigCenter;
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.utils.Log;
import com.backfire.utils.MyAsyncTask;
import com.backfire.utils.MyTaskWrap;

/**
 * @author wf
 * 
 */
public class RoomActivity extends ActivityThirdPlatform {
	private Room room;
	/** 存放每个座位seatidx上发的表情 **/
	private HashMap<Integer, AnimationChatToast> animationToastMap;
	private boolean isFinished = false;

	public AnimationClock animationClock = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		WakeLock.acquireCpuWakeLock(this, 1);
		AnimationManager.getInstance().clearAll();
//		WimiPaySdk.init(this);
		
		// RoomConfig.init();
		// Create Room
		room = new Room(this);
		room.loadAllRes();
		animationToastMap = new HashMap<Integer, AnimationChatToast>();
		(new Handler()).postDelayed(new Runnable() {

			@Override
			public void run() {
				// 加载房间音效资源
				new MyAsyncTask(new MyTaskWrap() {

					@Override
					public void onTaskStart() {
						DdzApplication.getApplication().initSound();
					}

					@Override
					public void onTaskFinish() {
					}
				}).execute();
			}

		}, 5000);
	}

	@Override
	protected void onResume() {
		ConfigCenter.volume_off = ShareData.getInstance().getBooleanValue(
				"VOLUME_OFF", false);
		DdzApplication.getApplication().getPlayMedia().startBgMusic();
		super.onResume();
	}

	@Override
	protected void onPause() {
		DdzApplication.getApplication().getPlayMedia().stopBgMusic();
		ConfigCenter.volume_off = true;
		super.onPause();
		// if(!isFinished){
		// toLobby();
		// }
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	/** 重置游戏 **/
	public void resetGame() {
		RoomInfo roomInfo = RoomInfo.getInstance();
		roomInfo.setState(GameState.GAME_REFIGHT);
		int accessMoney = roomInfo.getAccessMoney();
		if (UserMessageCenter.getInstance().getUserInfo().getMoney() < accessMoney) {
			room.showToast("再战失败,金钱不足");
			return;
		}
		RoomInfo.getInstance().clear();
		roomInfo.setRefight(true);
		room.resetGame();
	}

	public void addToast(int seatid, String msg) {
		int seatIdx = RoomInfo.getInstance().getSeatIdx(seatid);
		int posX = 0;
		int posY = 0;
		if (ConfigCenter.SeatPos1 != seatIdx) {
			posX = ConfigCenter.room_seat_X[seatIdx] + ConfigCenter.room_seat_W
					- ConfigCenter.room_chat_offset_W;
		} else {
			posX = ConfigCenter.room_seat_X[seatIdx] - ConfigCenter.room_chatW
					+ ConfigCenter.room_chat_offset_W;
		}
		if (ConfigCenter.SeatPos3 != seatIdx) {
			posY = ConfigCenter.room_seat_Y[seatIdx]
					+ ConfigCenter.room_seat_H
					- (ConfigCenter.room_seat_H - ConfigCenter.room_chat_offset_H);
		} else {
			posY = ConfigCenter.room_seat_Y[seatIdx] - ConfigCenter.room_chatH
					+ ConfigCenter.room_chat_offset_H;
		}
		int icon = ResCenter.getFitChatWordBorder(seatIdx);
		AnimationChatToast animationToast = animationToastMap.get(seatIdx);
		if (null != animationToast) {
			animationToastMap.remove(animationToast);
			AnimationManager.getInstance().removeAnimation(animationToast);
		}
		animationToast = new AnimationChatToast(seatid, icon, msg, posX, posY,
				seatIdx);
		animationToastMap.put(seatIdx, animationToast);

		AnimationManager.getInstance().addAnimation(animationToast, null);
	}

	@Override
	protected void onStop() {
		super.onStop();
		WakeLock.releaseCpuLock();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (null != room) {
			return room.onTouchEvent(event);
		}
		return true;
	}

	public void clickBackToLobby() {
		SelectPopupWindow select = new SelectPopupWindow(this, "你确定要退出游戏？", 0);
		select.setListens(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				WimiPaySdk.onDestroy();
				if (room != null && room.getSocketSender() != null) {
					// toLobby();
					room.getSocketSender().logoutReq();
				} else
					onLogoutSuccess();
			}
		}, null);
		select.ShowWindowInCenter();
	}

	public void toLobby() {
		if (!isFinished) {
			isFinished = true;
			ActivityContainer.getInstance().switchTo(RoomActivity.this,
					ActivityContainer.ActivityType.LOBBY_ACTIVITY);
			room.deInit();
			UserMessageCenter.getInstance().getUserInfo().removeServer();
			DdzApplication.getApplication().getPlayMedia().stopBgMusic();
			DdzApplication.getApplication().getPlayMedia().clear();
			DdzApplication.getApplication().clearPlayMedia();
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (ClickFilter.TestMultiClick())
			return false;
		if (!this.isFinishing()) {
			if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
					&& event.getAction() == KeyEvent.ACTION_DOWN) {
				Log.i(this, "click back");
				clickBackToLobby();
				return true;
			}
			return super.dispatchKeyEvent(event);
		}
		return false;
	}

	public Room getRoom() {
		return room;
	}

	public void onNetworkError(String msg) {
		if (RoomActivity.this != null && !RoomActivity.this.isFinishing()) {
			try {
				AlertPopupWindow alert = new AlertPopupWindow(this, msg, true);
				alert.setListens(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						onLogoutSuccess();
					}

				});
				Log.d(this, "show alert on NetworkError");
				alert.ShowWindowInCenter();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				onLogoutSuccess();
			}
		} else
			onLogoutSuccess();
	}

	public void onLogoutSuccess() {
		if (this != null && !isFinishing())
			toLobby();
	}

	public void showMessage(String msg) {
		try {
			AlertPopupWindow alert = new AlertPopupWindow(this, msg, true);
			alert.setListens(null);
			alert.ShowWindowInCenter();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			onLogoutSuccess();
		}
	}

	public void showSetWindow() {
		if (RoomActivity.this != null && !RoomActivity.this.isFinishing()) {
			try {
				SettingPopUpWindow popup = new SettingPopUpWindow(this);
				popup.setListens();
				popup.ShowWindowAtLocation(
						DdzApplication.getApplication().screenWidth / 2,
						DdzApplication.getApplication().screenHeight / 2);
			} catch (Exception e) {
				e.printStackTrace();
				onLogoutSuccess();
			}
		} else
			onLogoutSuccess();
	}

	public void showChatWindow() {
		if (RoomActivity.this != null && !RoomActivity.this.isFinishing()) {
			try {
				ChatPopupWindow popup = new ChatPopupWindow(this);
				popup.setListens(this);
				popup.ShowWindowInCenter();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				onLogoutSuccess();
			}
		} else
			onLogoutSuccess();
	}

	public void showOtherMsg(int seatid) {
		Player player = RoomInfo.getInstance().getPlayer(seatid);
		if (player != null) {
			long uid = 0;
			long money = 0;
			String nick = "";
			int icon = 0;
			int winCount = 0;
			long lottery = 0;
			String sign = "";
			int sex = 0;
			synchronized (player) {
				uid = player.getUid();
				money = player.getMoney();
				nick = player.getNick();
				icon = player.getIcon();
				winCount = player.getWinCount();
				lottery = player.getLottery();
				sex = player.getSex();
				sign = player.getSign();
			}
			OtherInfoPop otherpop = new OtherInfoPop(this, uid, icon, nick,
					sex, money, winCount, lottery, sign);
			otherpop.setListens();
			otherpop.ShowWindowInCenter();
		}
	}

	@Override
	public void rechargeSuccess(String msg) {
		Log.i(this, "roomActivity.........");
		showInfo(msg);
		Player player = RoomInfo.getInstance().getSelfPlayer();
		if (player != null) {
			synchronized (player) {
				player.setMoney(UserMessageCenter.getInstance().getUserInfo()
						.getMoney());
				player.setLottery(UserMessageCenter.getInstance().getUserInfo()
						.getLottery());
			}
		}
	}

	/** 补充金币 **/
	public void addVcoin() {
		Log.i(this, "addVcoin");
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("type", 1);
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new RechargeGoodsCallback(0),
				PHPMethodName.CLI_DIRECT_BUY_REQ, json);
		LoadingProgressDialog.show(this, "正在加载数据中...");
	}

	private class RechargeGoodsCallback implements PHPCallbackInterface {
		private long needMoney;

		public RechargeGoodsCallback(long money) {
			needMoney = money;
		}

		@Override
		public void onFinish(PHPResult result) {
			LoadingProgressDialog.dissmissDlg();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						JSONObject p = JSONUtil.getJSONObject(res, "products");
						final int pid = JSONUtil.getInt(p, "productID", 0);
						final int price = JSONUtil.getInt(p, "price", 0);
						String desc = JSONUtil.getString(p, "desc", "");
						final String payCode = JSONUtil
								.getString(p, "paycode", "");

						String giftinfo = JSONUtil.getString(p, "giftinfo", "");
						if (giftinfo.trim().length() > 0) {
							desc = desc + "," + Html.fromHtml(giftinfo);
						}

						getServerOrder(payCode, UserMessageCenter.getInstance()
								.getUserInfo().getUid(), pid, price, desc,
								needMoney);
					} else {
						// 登录失败
						int retCode = JSONUtil.getInt(res, "retCode", 0);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");

						AddStatistics.addCanNotPayStatistics(RoomActivity.this,
								"获取商品失败：" + msg + "(" + retCode + ")");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addCanNotPayStatistics(RoomActivity.this,
							"获取商品失败：数据包解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addCanNotPayStatistics(RoomActivity.this,
						"获取商品失败：网络异常异常");
			}
		}
	}

	@Override
	protected void orderFailed(final long needMoney) {
		LoadingProgressDialog.dissmissDlg();
		String msg = "充值不成功，请重试！";
		showMessage(msg);
		UserMessageCenter.getInstance().isGoodBuying = false;
	}

	@Override
	public String getTipBuy(long needMoney) {
		return null;
	}

	@Override
	public void updateUserMsgSuccess() {
		// TODO Auto-generated method stub

	}

	public void addClockAnimation(int posX, int posY, int timeOut) {
		animationClock = new AnimationClock(timeOut, posX, posY);
		AnimationManager.getInstance().addAnimation(animationClock);
	}

	public void addClockAnimation(int seatid, int timeOut) {
		if (seatid <= 0)
			return;
		RoomInfo roomInfo = RoomInfo.getInstance();
		synchronized (roomInfo) {
			roomInfo.setCurrentActionSeatId(seatid);
		}
		int seatIdx = roomInfo.getSeatIdx(seatid);
		int posX = ConfigCenter.clock_X[seatIdx];
		int posY = ConfigCenter.clock_Y[seatIdx];
		removeClockAnimation();
		animationClock = new AnimationClock(timeOut, posX, posY);
		AnimationManager.getInstance().addAnimation(animationClock);
	}

	public void removeClockAnimation() {
		if (null != animationClock) {
			AnimationManager.getInstance().removeAnimation(animationClock);
		}
	}
}
