
package com.lianxin.pubqq.ulive;

import java.util.List;

import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.lianxin.panqq.list.adpter.BaseRoomAdapter;
import com.lianxin.panqq.list.bean.Member;
import com.lianxin.pubqq.R;
import com.lianxin.pubqq.ulive.adpter.VideoHeadGridAdapter;
import com.lianxin.pubqq.ulive.adpter.VideoHeadGridAdapter.OnMyHeadClickListener;
import com.lianxin.pubqq.ulive.adpter.VideoPlayGridAdapter;
import com.lianxin.pubqq.ulive.adpter.VideoPlayGridAdapter.OnMyItemClickListener;
import com.lianxin.panqq.widget.ExpandGridView;
import com.lianxin.panqq.common.DefineUser;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.PermissionChecker;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.chat.BaseMediaActivity;
import com.lianxin.panqq.chat.EMMediaCallHelper;
import com.lianxin.panqq.chat.EMMediaManager;
import com.lianxin.panqq.chat.entity.EMRoomStateChangeListener;
import com.lianxin.panqq.chat.utils.CameraHelper;
import com.lianxin.panqq.utils.ImagesUtils;

//视频群聊(用户自己选择看谁不看谁)
public class GroupVideoActivity extends BaseMediaActivity implements
		OnClickListener {
	
    private SurfaceView surFaceView = null;
	private SurfaceHolder surFaceHolder;  
	private EMMediaCallHelper callHelper;
	private CameraHelper cameraHelper;	

	private TextView txt_title;	 //对话框标题
	private TextView cap_groupname; //群组标题
	private TextView tv_groupname; //群组名称	
	private TextView cap_groupid; //群组id标题
	private TextView tv_groupid; //群组id	
//	private TextView txt_title;// 标题，成员总数
//	int m_total = 0;// 成员总数
	private ExpandGridView gridview;// 成员列表
	private ExpandGridView headview;// 成员列表
	private  VideoHeadGridAdapter headadapter;
	private  VideoPlayGridAdapter playadapter;	
	// 修改群名称、置顶、、、、
	//private RelativeLayout re_groupname;
	//private RelativeLayout re_state;

	// 状态变化
	private CheckBox check_camera, check_speaker;
	private Button startBtn,exitBtn;
	private TextView roomStateTextView;	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);	
		setContentView(R.layout.live_activity_groupvideo);	
		
        //android 6.0及以上申请相机权限    
        String[] Permissions = {
        		Manifest.permission.CAMERA,
              Manifest.permission.READ_PHONE_STATE
              };        
        PermissionChecker Checker = new PermissionChecker(this);        
        Checker.checkPermissions(this,Permissions,new PermissionChecker.PermissionCheckCallback() { 
			@Override
			public void onRequest() {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onGranted() {
					
			}

			@Override
			public void onGrantSuccess() {			
	
			}
			@Override
			public void onGrantFail() {
	            return;
			}

		});		
		
		mediaMode = 2;
		initControl();
		initMedia(); //初始化群聊环境
		initGroupData();//初始化群聊成员数据
		initView();	
	   //    initSurface();  //必须此处初始化亮度、声音 		
		setListener();
		// 设置房间监听
		addRoomStateListener();		
	}

	protected void initControl() {
		//注释性控件
		txt_title = (TextView) findViewById(R.id.txt_title);
		cap_groupname = (TextView) findViewById(R.id.cap_groupname);
		tv_groupname = (TextView) findViewById(R.id.txt_groupname);	
		cap_groupid = (TextView) findViewById(R.id.cap_groupid);
		tv_groupid = (TextView) findViewById(R.id.txt_groupid);
		//主控件
		gridview = (ExpandGridView) findViewById(R.id.gridview);
		headview = (ExpandGridView) findViewById(R.id.headview);

		check_camera = (CheckBox)findViewById(R.id.check_camera);
		check_speaker = (CheckBox)findViewById(R.id.check_speaker);
		
		exitBtn = (Button) findViewById(R.id.btn_exit_talk);
		startBtn = (Button) findViewById(R.id.btn_start_talk);	
		roomStateTextView = (TextView) findViewById(R.id.tv_room_state);		
	}

	protected void initSurface() {
		// 显示本地图像的surfaceview
		surFaceView = (SurfaceView) findViewById(R.id.local_surface);
		surFaceView.setZOrderMediaOverlay(true);
		surFaceView.setZOrderOnTop(true);
		surFaceHolder = surFaceView.getHolder();

		surFaceHolder.addCallback(new localCallback());
		// 设置该SurfaceView自己不维护缓冲
		surFaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		// 获取callHelper,cameraHelper//发送接口
		callHelper = EMMediaCallHelper.getInstance();
		callHelper.setSurfaceView(mPlayId, surFaceView);
		callHelper.setGridAdapter( (BaseRoomAdapter)headadapter, (BaseRoomAdapter)playadapter );	
		cameraHelper = new CameraHelper(callHelper, surFaceHolder);
		// cameraHelper.startCapture();
		//surFaceView.setVisibility(View.INVISIBLE);
	}
	   
	/**
	* 本地SurfaceHolder callback
	* 
	*/
	class localCallback implements SurfaceHolder.Callback {

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			cameraHelper.startCapture();
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
		}
	}
 	   
	//@Override
	protected void initView() {
		setCaption();
		// 显示群组成员头像和昵称
		//if (members != null)
		showMembersPlay(players);
		showMembersHead(members);
	}


    //按照类别设置标题
	protected void setCaption() {
		tv_groupid.setText(""+groupId);		
		tv_groupname.setText(groupName);		
		switch (groupType) {
		case DefineUser.TYPE_FRIEND:
			txt_title.setText("群聊");
			cap_groupid.setText("分类ID");
			cap_groupname.setText("分类名称");
			//cap_type.setText("关  键  字");
			//cap_enyear.setText("兴趣地域");	
			break;		
		case DefineUser.TYPE_CROWD:
			txt_title.setText("视频群聊");
			cap_groupid.setText("群ID");
			cap_groupname.setText("群名称");
			//cap_type.setText("关  键  字");
			//cap_enyear.setText("兴趣地域");			
			break;
		case DefineUser.TYPE_MYCLASS:
			txt_title.setText("班视频群聊");
			cap_groupid.setText("班ID");
			cap_groupname.setText("班名称");
			//cap_type.setText("所属院系");
			//cap_enyear.setText("入学年份");	
			break;
		case DefineUser.TYPE_DEPART:
			txt_title.setText("部门视频群聊");
			cap_groupid.setText("部门ID");
			cap_groupname.setText("部门名称");
			//cap_type.setText("所属父项");
			//cap_enyear.setText("主管部门");	
			break;		
		case DefineUser.TYPE_PARTY:
			txt_title.setText("会议室视频群聊");
			cap_groupid.setText("会议ID");
			cap_groupname.setText("会议名称");
			//cap_type.setText("所属父项");
			//cap_enyear.setText("主管部门");	
			break;
		case DefineUser.TYPE_GROUP:
			txt_title.setText("俱乐部视频群聊");
			cap_groupid.setText("俱乐部ID");
			cap_groupname.setText("俱乐部名");
			//cap_type.setText("所属省份");
			//cap_enyear.setText("所在城市");	
			break;
		case DefineUser.TYPE_CITY:
			txt_title.setText("地域视频群聊");
			cap_groupid.setText("地域ID");
			cap_groupname.setText("地域名称");
			//cap_type.setText("所属省份");
			//cap_enyear.setText("所在城市");	
			break;		
	
		default:
			txt_title.setText("视频群聊");
			cap_groupid.setText("群ID");
			cap_groupname.setText("群名称");
			//cap_type.setText("关  键  字");
			//cap_enyear.setText("兴趣地域");				
			break;
		}			
	}	
	// 显示群成员头像昵称的gridview
	private void showMembersPlay(List<Member> members) {
		playadapter = new VideoPlayGridAdapter(this, members);
		gridview.setAdapter(playadapter);
		playadapter.setGridView(gridview);
		playadapter.setMyItemClickListener(new OnMyItemClickListener(){  
			@Override
			public void onItemClicked( int userid, Member user, int position) {
				//Member user = members.get(position);
			//	Member user = null;				
				deleteMemberFromPlayers(user);
			} 
	 			
        });		
	}

	// 显示群成员头像昵称的gridview
	private void showMembersHead(List<Member> members) {
		//headadapter = new HeadGridAdapter(this, members);
		//headview.setAdapter(headadapter);
		headadapter = new VideoHeadGridAdapter(this, members);
		headview.setAdapter(headadapter);
		headadapter.setGridView(headview);
		headadapter.setMyItemClickListener(new OnMyHeadClickListener(){  
			@Override
			public void onItemClicked( int userid, Member user, int position) {
				addPlayerFromMembers(user);
			} 
	 			
        });	
	}

	protected void setListener() {
		check_camera.setChecked(true);
		check_speaker.setChecked(true);		
		//re_groupname.setOnClickListener(this);
		//rl_switch_camera.setOnClickListener(this);
		//rl_switch_speaker.setOnClickListener(this);
		//re_state.setOnClickListener(this);
		exitBtn.setOnClickListener(this);
		startBtn.setOnClickListener(this);		
		check_camera.setOnClickListener(this);
		check_speaker.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.img_back) {
			Utils.finish(GroupVideoActivity.this);
		} else if (id == R.id.btn_exit_talk) {
			postHanderMessage(MSG_MEDIA_EXITROOM, 10000);
			//Utils.finish(GroupVideoActivity.this);
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
			}
			//finish();
			Utils.finish(GroupVideoActivity.this);
		} else if (id == R.id.btn_start_talk) {
			postHanderMessage(MSG_MEDIA_JOINROOM, 10000);
			initSurface();
			// 通知cameraHelper可以写入数据
			cameraHelper.setStartFlag(true);
			cameraHelper.startCapture();
			//case R.id.rl_switch_camera:
			//	isOpenCamera = !isOpenCamera;
			//	break;
			//case R.id.rl_switch_speaker:
			//	isOpenSpeaker = !isOpenSpeaker;
			//	break;
		} else if (id == R.id.check_camera) {
			isOpenCamera = ((CheckBox) v).isChecked();
			if (isOpenCamera)
				postHanderMessage(MSG_MEDIA_STARTSEND_VIDEO, 10000);
			else
				postHanderMessage(MSG_MEDIA_STOPSEND_VIDEO, 10000);
		} else if (id == R.id.check_speaker) {
			isOpenSpeaker = ((CheckBox) v).isChecked();
			if (isOpenCamera)
				postHanderMessage(MSG_MEDIA_STARTSEND_VOICE, 10000);
			else
				postHanderMessage(MSG_MEDIA_STOPSEND_VOICE, 10000);
		}
	}

	@Override
	protected void onDestroy() {
		
		stHandler.sendEmptyMessage(MSG_MEDIA_EXITROOM);
        try {
        	if(callHelper != null)
			callHelper.setSurfaceView(10000,null);
        	if(cameraHelper != null)       	
			cameraHelper.stopCapture();
			cameraHelper = null;
		} catch (Exception e) {
		}
		super.onDestroy();        

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		//moveTaskToBack(true);		
	}

    protected void onUpdateMember(){
    	headadapter.setData(members); 
    	playadapter.setData(players);   	
    }
  
	public void refresh() {
    	headadapter.notifyDataSetChanged(); 
    	playadapter.notifyDataSetChanged();
	}	
	
	/**
	 * 设置房间状态监听
	 */
	void addRoomStateListener() {
		EMMediaManager.getInstance().addRoomStateChangeListener(
			new EMRoomStateChangeListener() {
				@Override
				public void onError(int errorCode, String errorMessage) {
					final String str = errorMessage;
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
								// callStateTextView.setText(str);
						}
					});
				}

				@Override
				public void onProgress(int progress, String status) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							String str = "发送" + GloableParams.n_MediaSendCount
										+ " 接收" + GloableParams.n_MediaRecvCount;
							roomStateTextView.setText(str);
						}
					});
				}

				@Override
				public void onCallStateChanged(CallState callState,
							CallError error) {

				}

				@Override
				public void onUserHeadCome(int userid, int status) {
					final int sendid = userid;					
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							playadapter.updateItemThumb(sendid);
						}
					});
				}				
				
				@Override
				public void onUserTextCome(int userid, String message) {

				}

				@Override
				public void onUserCustomCome(int userid, byte[] data,
							int length) {

				}

				@Override
				public void onUserJoinRoom(int userid, String status) {
					String str = "自己（"+ userid + "）进入了";					
					roomStateTextView.setText(str);
				}

				@Override
				public void onUserExitRoom(int userid, String status) {
					String str = "自己（"+ userid + "）退出了";					
					roomStateTextView.setText(str);
				}
				
				@Override
				public void onOtherJoinRoom(int userid, String name) {
					String str = name + "（"+ userid + "）进入了";					
					roomStateTextView.setText(str);
				}

				@Override
				public void onOtherExitRoom(int userid, String name) {
					String str = name + "（"+ userid + "）退出了";					
					roomStateTextView.setText(str);
				}				
			});
	}	
}
