package com.backfire.room;

import net.yeeyo.doudizhu.feiyu.R;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PaintFlagsDrawFilter;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.backfire.Animation.Animation;
import com.backfire.Animation.AnimationManager.IAnimationCallback;
import com.backfire.doudizhu.common.CriticalPool;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.userinfo.UserMessageCenter;
import com.backfire.graphics.PCanvas;
import com.backfire.popupwindow.SettleAccountWindow;
import com.backfire.room.Interface.IClickListener;
import com.backfire.room.data.ConfigCenter;
import com.backfire.room.data.HandlerMsg;
import com.backfire.room.data.RoomInfo;
import com.backfire.room.data.State.GameState;
import com.backfire.room.data.State.SeatS;
import com.backfire.room.manager.BtnManagerCenter;
import com.backfire.room.manager.CardButtonManager;
import com.backfire.room.receiveDataManager.BroadcastProtoManager;
import com.backfire.room.receiveDataManager.UserProtoManager;
import com.backfire.room.surface.AnimationSurface;
import com.backfire.room.surface.RoomSurface;
import com.backfire.room.surface.UserSurface;
import com.backfire.socket.SocketDataSend;
import com.backfire.utils.Log;

/**
 * @author wf
 * 
 */
public class Room implements IClickListener, IAnimationCallback {
	private SocketDataSend socketSender = null;

	private CanvasSurfaceView mView = null;
	private RoomRenderer mRender = null;
	private RoomActivity mContext = null;
	private boolean binit = false;

	private RoomSurface roomSurface = null;
	private UserSurface userSurFace = null;
	private AnimationSurface animationSurface = null;

	private BtnManagerCenter btnManager = null;
	private CardButtonManager cardManager = null;

	public UserProtoManager userProtoManager = null;
	public BroadcastProtoManager broadcastProtoManager = null;

	private MsgDispatcher msgDispatcher = null;

	private Bitmap loading_bg = null;

	public Room(RoomActivity context) {
		mContext = context;
		mView = new CanvasSurfaceView(context);
		mRender = new RoomRenderer();
		mView.setRenderer(mRender, DdzApplication.getApplication().screenWidth,
				DdzApplication.getApplication().screenHeight);
		binit = false;
		RelativeLayout tmpLayout = new RelativeLayout(mContext);
		tmpLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));

		tmpLayout.addView(mView);
		mContext.setContentView(tmpLayout);

		loading_bg = DdzApplication
				.getApplication()
				.getBmpPool()
				.getBitmap(R.drawable.waitting_bg,
						DdzApplication.getApplication().screenWidth,
						DdzApplication.getApplication().screenHeight);

	}

	public void loadAllRes() {
		roomSurface = new RoomSurface();
		userSurFace = new UserSurface(this);
		animationSurface = new AnimationSurface();

		btnManager = new BtnManagerCenter(this, this);
		cardManager = new CardButtonManager(mContext);
		userProtoManager = new UserProtoManager(mContext);
		broadcastProtoManager = new BroadcastProtoManager(mContext);

		this.setSocketSender(new SocketDataSend(this));
		this.getSocketSender().Connect(
				UserMessageCenter.getInstance().getUserInfo().getTableIP(),
				UserMessageCenter.getInstance().getUserInfo().getTablePort());
		msgDispatcher = new MsgDispatcher(mContext);

		binit = true;
	}

	public void deInit() {
		close();
		binit = false;
		if (userProtoManager != null)
			userProtoManager = null;
		if (broadcastProtoManager != null)
			broadcastProtoManager = null;
		RoomInfo.getInstance().clearAll();

		if (btnManager != null) {
			synchronized (btnManager) {
				btnManager.clearAll();
			}
			btnManager = null;
		}
		if (cardManager != null) {
			synchronized (cardManager) {
				cardManager.clearAll();
			}
			cardManager = null;
		}
		// 卸载音效
		DdzApplication.getApplication().deInitSound();
		DdzApplication.getApplication().clearBmpPool();
	}

	public SocketDataSend getSocketSender() {
		return socketSender;
	}

	private void setSocketSender(SocketDataSend socketSender) {
		this.socketSender = socketSender;
	}

	public void close() {
		Log.d(this, "Close Room and Socket");
		if (socketSender != null) {
			socketSender.close();
			setSocketSender(null);
		}
	}

	public void onNetworkError(String msg) {
		if (mContext != null && !mContext.isFinishing())
			mContext.onNetworkError(msg);
	}

	public void onLogoutSuccess(String msg) {
		if (msg != null)
			DdzApplication.getApplication().showToast(msg);
		if (mContext != null && !mContext.isFinishing())
			mContext.onLogoutSuccess();
	}

	public class RoomRenderer implements CanvasSurfaceView.Renderer {
		private PaintFlagsDrawFilter drawFilter;

		public RoomRenderer() {
			drawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
					| Paint.FILTER_BITMAP_FLAG);
		}

		public void sizeChanged(int width, int height) {

		}

		@Override
		public void drawFrame(PCanvas canvas, int sum, int rate, long sleep) {
			canvas.setDrawFilter(drawFilter);
			if (binit) {
				try {
					RoomInfo roomInfo = RoomInfo.getInstance();
					int gameState = roomInfo.getState();
					boolean isRebinding = roomInfo.isRebinding();
					if (gameState >= 0 && !isRebinding) {
						int selfState = roomInfo.getSelfPlayerState();
						if (null != roomSurface) {
							roomSurface.draw(canvas, gameState, selfState);
						}

						if (null != userSurFace) {
							userSurFace.draw(canvas, gameState, selfState);
						}

						if (gameState < GameState.GAME_REFIGHT) {
							if (null != cardManager) {
								cardManager.draw(canvas, gameState, selfState);
							}

							if (null != btnManager) {
								btnManager.draw(canvas, gameState);
							}

							if (null != animationSurface) {
								animationSurface.drawSelf(canvas, sleep);
							}
						}

//						Paint paint = CriticalPool.getPaint();
//						paint.setColor(Color.RED);
//						paint.setTextSize(20);
//						canvas.drawText(
//								String.format("%02d/%02d", rate, sleep), 1, 20,
//								paint);
					} else {// 加载界面
						canvas.drawBitmap(loading_bg, 0, 0, null);

						Paint paint = CriticalPool.getPaint();
						paint.setTextSize(ConfigCenter.loadingTextFrontSize);
						paint.setFakeBoldText(true);
						paint.setTextAlign(Align.CENTER);
						paint.setColor(Color.WHITE);
						canvas.drawText(
								"加载中.....",
								DdzApplication.getApplication().screenWidth / 2,
								DdzApplication.getApplication().screenHeight
										* (1 - 1 / (float) 4), paint);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void showToast(String message) {
		if (mContext != null && !mContext.isFinishing()) {
			Toast toast = Toast.makeText(mContext, message, Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
	}

	@Override
	public void sendMsg(int msg) {
		msgDispatcher.sendEmptyMessage(msg);
	}

	public void showSettleAccountWindow() {
		SettleAccountWindow settleAccountWindow = new SettleAccountWindow(
				mContext);
		settleAccountWindow.registerListenerInfo(
				HandlerMsg.MSG_SETTLE_ACCOUNT_EXIT,
				HandlerMsg.MSG_SETTLE_ACCOUNT_REFIGHT, this);
		try {
			Thread.sleep(3000);// 休眠3秒，然后弹出款
			settleAccountWindow.ShowWindowInCenter();
		} catch (Exception e) {
			Log.i(this, e);
		}
	}

	public void resetGame() {
		if (socketSender != null) {
			socketSender.seatReq(SeatS.SIT);
			socketSender.readyReq();
		}
		if (userSurFace != null) {
			synchronized (userSurFace) {
				userSurFace.reset();
			}
		}
		if (btnManager != null) {
			synchronized (btnManager) {
				btnManager.reset();
			}
		}
		if (cardManager != null) {
			synchronized (cardManager) {
				cardManager.clear();
			}
		}
	}

	public UserSurface getUserSurFace() {
		return userSurFace;
	}

	public RoomActivity getmContext() {
		return mContext;
	}

	public void setmContext(RoomActivity mContext) {
		this.mContext = mContext;
	}

	public boolean onTouchEvent(MotionEvent event) {
		boolean result = false;
		if (btnManager != null) {
			synchronized (btnManager) {
				result = btnManager.dispatch(event);
			}
		}
		if (!result) {
			if (userSurFace != null) {
				synchronized (userSurFace) {
					result = userSurFace.dispatch(event);
				}
			}
		}
		if (!result && GameState.GAME_PLAY == RoomInfo.getInstance().getState()) {
			if (cardManager != null) {
				synchronized (cardManager) {
					cardManager.dispatch(event);
				}
			}
		}
		return result;
	}

	public void updateManagerBtn() {
		if (null != btnManager
				&& GameState.GAME_LOADING != RoomInfo.getInstance().getState()) {
			synchronized (btnManager) {
				btnManager.updateState();
			}
		}
	}

	public CardButtonManager getCardBtnManager() {
		return cardManager;
	}

	public BtnManagerCenter getBtnManager() {
		return btnManager;
	}

	@Override
	public void animeWillFinished(Animation anim) {
		RoomInfo.getInstance().setLastLaiziSeaCardDisplay(true);// 设置最后一张癞子牌显示
	}
}
