
package com.lianxin.pubqq.chat;
import java.util.UUID;

import android.Manifest;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.R;
import com.lianxin.pubqq.activity.GroupInfoActivity;
import com.lianxin.pubqq.ulive.GroupVideoActivity;
import com.lianxin.panqq.chat.utils.CameraHelper;
//import com.lianxin.panqq.chat.BaseCallActivity;
import com.lianxin.panqq.chat.BaseCallActivity;
import com.lianxin.panqq.chat.BaseCallActivity.CallingState;
import com.lianxin.panqq.chat.EMCallManager;
//import com.lianxin.panqq.main.EMChatManager;
import com.lianxin.panqq.chat.entity.EMCallStateChangeListener;
import com.lianxin.panqq.chat.EMVideoCallHelper;
import com.lianxin.panqq.chat.entity.EMCallStateChangeListener.CallError;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.PermissionChecker;
//import com.lianxin.panqq.chat.entity.IMCallManager;
import com.lianxin.panqq.common.Utils;
public class VideoCallActivity extends BaseCallActivity implements OnClickListener {

	private SurfaceView localSurface;
	private SurfaceHolder localSurfaceHolder;
	private static SurfaceView oppositeSurface;
	private SurfaceHolder oppositeSurfaceHolder;

	private boolean isMuteState;
	private boolean isHandsfreeState;
	private boolean isAnswered;
	private int streamID;
	private boolean endCallTriggerByMe = false;

	EMVideoCallHelper callHelper;
	private TextView callStateTextView;

	private Handler handler = new Handler();
	private LinearLayout comingBtnContainer;
	private Button refuseBtn;
	private Button answerBtn;
	private Button hangupBtn;
	private ImageView muteImage;
	private ImageView switchbtn;	
	private ImageView handsFreeImage;
	private TextView nickTextView;
	private Chronometer chronometer;
	private LinearLayout voiceContronlLayout;
	private RelativeLayout rootContainer;
	private RelativeLayout btnsContainer;
	private CameraHelper cameraHelper;
	private LinearLayout topContainer;
	private LinearLayout bottomContainer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_call);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
						| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		callStateTextView = (TextView) findViewById(R.id.tv_call_state);
		comingBtnContainer = (LinearLayout) findViewById(R.id.ll_coming_call);
		rootContainer = (RelativeLayout) findViewById(R.id.root_layout);
		refuseBtn = (Button) findViewById(R.id.btn_refuse_call);
		answerBtn = (Button) findViewById(R.id.btn_answer_call);
		hangupBtn = (Button) findViewById(R.id.btn_hangup_call);
		muteImage = (ImageView) findViewById(R.id.iv_mute);
		switchbtn = (ImageView) findViewById(R.id.switch_btn);		
		handsFreeImage = (ImageView) findViewById(R.id.iv_handsfree);
		callStateTextView = (TextView) findViewById(R.id.tv_call_state);
		nickTextView = (TextView) findViewById(R.id.tv_nick);
		chronometer = (Chronometer) findViewById(R.id.chronometer);
		voiceContronlLayout = (LinearLayout) findViewById(R.id.ll_voice_control);
		btnsContainer = (RelativeLayout) findViewById(R.id.ll_btns);
		topContainer = (LinearLayout) findViewById(R.id.ll_top_container);
		bottomContainer = (LinearLayout) findViewById(R.id.ll_bottom_container);

		refuseBtn.setOnClickListener(this);
		answerBtn.setOnClickListener(this);
		hangupBtn.setOnClickListener(this);
		muteImage.setOnClickListener(this);
		switchbtn.setOnClickListener(this);		
		handsFreeImage.setOnClickListener(this);
		rootContainer.setOnClickListener(this);

		callmode = 1;		
		msgid = UUID.randomUUID().toString();
		// 获取通话是否为接收方向的
		isInComingCall = getIntent().getBooleanExtra("isComingCall", false);
		username = getIntent().getStringExtra("username");
		userid = getIntent().getIntExtra("userid",10002);
		initCallInfo();		
		// 设置通话人
		nickTextView.setText(username);

        //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;
			}

		});		
		
		// 显示本地图像的surfaceview
		localSurface = (SurfaceView) findViewById(R.id.local_surface);
		localSurface.setZOrderMediaOverlay(true);
		localSurface.setZOrderOnTop(true);
		localSurfaceHolder = localSurface.getHolder();

		// 获取callHelper,cameraHelper//发送接口
		callHelper = EMVideoCallHelper.getInstance();
		cameraHelper = new CameraHelper(callHelper, localSurfaceHolder);

		// 显示对方图像的surfaceview
		oppositeSurface = (SurfaceView) findViewById(R.id.opposite_surface);
		oppositeSurfaceHolder = oppositeSurface.getHolder();
		// 设置显示对方图像的surfaceview//接收接口
		callHelper.setSurfaceView(userid,oppositeSurface);

		localSurfaceHolder.addCallback(new localCallback());
		oppositeSurfaceHolder.addCallback(new oppositeCallback());
        // 设置该SurfaceView自己不维护缓冲 		
		localSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		oppositeSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		// 设置通话监听
		addCallStateListener();

	//	localSurfaceHolder.addCallback(new localCallback());
	//	oppositeSurfaceHolder.addCallback(new oppositeCallback());
		if (!isInComingCall) {// 拨打电话
			soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
			outgoing = soundPool.load(this, R.raw.outgoing, 1);

			comingBtnContainer.setVisibility(View.INVISIBLE);
			hangupBtn.setVisibility(View.VISIBLE);
			String st = getResources().getString(
					R.string.Are_connected_to_each_other);
			callStateTextView.setText(st);

			handler.postDelayed(new Runnable() {
				public void run() {
					streamID = playMakeCallSounds();
				}
			}, 300);
		} else { // 有电话进来
			voiceContronlLayout.setVisibility(View.INVISIBLE);
			localSurface.setVisibility(View.INVISIBLE);
			refuseBtn.setVisibility(View.VISIBLE);			
			Uri ringUri = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
			audioManager.setMode(AudioManager.MODE_RINGTONE);
			audioManager.setSpeakerphoneOn(true);
			ringtone = RingtoneManager.getRingtone(this, ringUri);
			ringtone.play();
		}
		if (!isInComingCall) {// 拨打电话
			// 拨打视频通话
			//EMCallManager.getInstance().makeVideoCall(username);
			EMCallManager.getInstance().makeVideoCall(userid);				
			// 通知cameraHelper可以写入数据
			cameraHelper.setStartFlag(true);		
		}
	//	cameraHelper.setStartFlag(true);		
	//	saveCallRecord(1);		
	}

	/**
	 * 本地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) {
		}
	}

	/**
	 * 对方SurfaceHolder callback
	 */
	class oppositeCallback implements SurfaceHolder.Callback {

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			if(callHelper != null)		
			callHelper.onWindowResize(width, height, format);
			if(cameraHelper == null){			
			}else if (!cameraHelper.isStarted()) {
				if (!isInComingCall) {
				//	try {
						// 拨打视频通话
						//EMCallManager.getInstance().makeVideoCall(username);
						EMCallManager.getInstance().makeVideoCall(userid);				
						// 通知cameraHelper可以写入数据
						cameraHelper.setStartFlag(true);
				}

			} else {
			}
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
		}

	}

	/**
	 * 设置通话状态监听
	 */
	void addCallStateListener() {
		EMCallManager.getInstance().addVoiceCallStateChangeListener(		
				new EMCallStateChangeListener() {
					@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;								
								callStateTextView.setText(str);
							}
						});
				    }					
					@Override
					public void onCallStateChanged(CallState callState,
							CallError error) {
						switch (callState) {

						case CONNECTING: // 正在连接对方
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									String st2 = getResources()
											.getString(
													R.string.Are_connected_to_each_other);
									callStateTextView.setText(st2);
								}

							});
							break;
						case CONNECTED: // 双方已经建立连接
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									String st3 = getResources().getString(
											R.string.have_connected_with);
									callStateTextView.setText(st3);
								}

							});
							break;

						case ACCEPTED: // 电话接通成功
					/*		comingBtnContainer.setVisibility(View.INVISIBLE);
							hangupBtn.setVisibility(View.VISIBLE);
							voiceContronlLayout.setVisibility(View.VISIBLE);
							localSurface.setVisibility(View.VISIBLE);	*/						
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									try {
										if (soundPool != null)
											soundPool.stop(streamID);
									} catch (Exception e) {
									}
									openSpeakerOn();
									handsFreeImage
											.setImageResource(R.drawable.icon_speaker_on);
									isHandsfreeState = true;
									chronometer.setVisibility(View.VISIBLE);
									chronometer.setBase(SystemClock
											.elapsedRealtime());
									// 开始记时
									chronometer.start();
									nickTextView.setVisibility(View.INVISIBLE);
									String st5 = getResources().getString(
											R.string.In_the_call);
									callStateTextView.setText(st5);
									callingState = CallingState.NORMAL;
									/*	int width = CameraHelper.mParameters.getPreviewSize().width;
									int height = CameraHelper.mParameters.getPreviewSize().height;
									String str = "size:"+width+"x"+height;
									callStateTextView.setText(str);	*/									
									cameraHelper.setStartFlag(true);									
								}

							});
							break;
						case DISCONNNECTED: // 电话断了
							final CallError fError = error;
							runOnUiThread(new Runnable() {
								private void postDelayedCloseMsg() {
									handler.postDelayed(new Runnable() {

										@Override
										public void run() {
											saveCallRecord(1);
											/*低版本运行正常,高版本崩溃						
											Animation animation = new AlphaAnimation(
													1.0f, 0.0f);
											animation.setDuration(800);
											rootContainer
													.startAnimation(animation);*/
									//		finish();
											Utils.finish(VideoCallActivity.this);										
										}

									}, 200);
								}

								@Override
								public void run() {
									chronometer.stop();
									callDruationText = chronometer.getText()
											.toString();
									String s1 = getResources()
											.getString(
													R.string.The_other_party_refused_to_accept);
									String s2 = getResources().getString(
											R.string.Connection_failure);
									String s3 = getResources()
											.getString(
													R.string.The_other_party_is_not_online);
									String s4 = getResources()
											.getString(
													R.string.The_other_is_on_the_phone_please);
									String s5 = getResources()
											.getString(
													R.string.The_other_party_did_not_answer);

									String s6 = getResources().getString(
											R.string.hang_up);
									String s7 = getResources().getString(
											R.string.The_other_is_hang_up);
									String s8 = getResources().getString(
											R.string.did_not_answer);
									String s9 = getResources().getString(
											R.string.Has_been_cancelled);

									if (fError == CallError.REJECTED) {
										callingState = CallingState.BEREFUESD;
										callStateTextView.setText(s1);
									} else if (fError == CallError.ERROR_TRANSPORT) {
										callStateTextView.setText(s2);
									} else if (fError == CallError.ERROR_INAVAILABLE) {
										callingState = CallingState.OFFLINE;
										callStateTextView.setText(s3);
									} else if (fError == CallError.ERROR_BUSY) {
										callingState = CallingState.BUSY;
										callStateTextView.setText(s4);
									} else if (fError == CallError.ERROR_NORESPONSE) {
										callingState = CallingState.NORESPONSE;
										callStateTextView.setText(s5);
									} else if (fError == CallError.CANCED) {
										callingState = CallingState.CANCED;
										callStateTextView.setText(s9);										
									} else {
										if (isAnswered) {
											callingState = CallingState.NORMAL;
											if (endCallTriggerByMe) {
												callStateTextView.setText(s6);
											} else {
												callStateTextView.setText(s7);
											}
										} else {
											if (isInComingCall) {
												callingState = CallingState.UNANSWERED;
												callStateTextView.setText(s8);
											} else {
												if (callingState != CallingState.NORMAL) {
													callingState = CallingState.CANCED;
													callStateTextView
															.setText(s9);
												} else {
													callStateTextView
															.setText(s6);
												}
											}
										}
									}
									postDelayedCloseMsg();
								}

							});

							break;

						default:
							break;
						}

					}
				});
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_refuse_call) { // 拒绝接听
			if (ringtone != null)
				ringtone.stop();
			/*try {
				EMCallManager.getInstance().rejectCall(2);
			} catch (Exception e1) {
				e1.printStackTrace();
				saveCallRecord(1);
				finish();
			}*/
			stHandler.sendEmptyMessage(MSG_CALL_REJECT_VIDEO);
			callingState = CallingState.REFUESD;
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
			}
			//finish();
			Utils.finish(VideoCallActivity.this);
		} else if (id == R.id.btn_answer_call) { // 接听电话
			comingBtnContainer.setVisibility(View.INVISIBLE);
			hangupBtn.setVisibility(View.VISIBLE);
			voiceContronlLayout.setVisibility(View.VISIBLE);
			localSurface.setVisibility(View.VISIBLE);
			if (ringtone != null)
				ringtone.stop();

			if (isInComingCall) {
				//if (true) {
				try {
					isAnswered = true;
					//EMCallManager.getInstance().answerCall(2);
					stHandler.sendEmptyMessage(MSG_CALL_ANSWER_VIDEO);
					//cameraHelper.setStartFlag(true);

					openSpeakerOn();
					handsFreeImage.setImageResource(R.drawable.icon_speaker_on);
					isHandsfreeState = true;
					cameraHelper.setStartFlag(true);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					saveCallRecord(1);
					finish();
				}
			}
		} else if (id == R.id.btn_hangup_call) { // 挂断电话

			stHandler.sendEmptyMessage(MSG_CALL_END_VIDEO);
			cameraHelper.setStartFlag(false);

			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
			}
			//finish();
			Utils.finish(VideoCallActivity.this);
		} else if (id == R.id.iv_mute) { // 静音开关
			if (isMuteState) {
				// 关闭静音
				muteImage.setImageResource(R.drawable.icon_mute_normal);
				audioManager.setMicrophoneMute(false);
				isMuteState = false;
			} else {
				// 打开静音
				muteImage.setImageResource(R.drawable.icon_mute_on);
				audioManager.setMicrophoneMute(true);
				isMuteState = true;
			}
		} else if (id == R.id.iv_handsfree) { // 免提开关
			if (isHandsfreeState) {
				// 关闭免提
				handsFreeImage.setImageResource(R.drawable.icon_speaker_normal);
				closeSpeakerOn();
				isHandsfreeState = false;
			} else {
				handsFreeImage.setImageResource(R.drawable.icon_speaker_on);
				openSpeakerOn();
				isHandsfreeState = true;
			}
		} else if (id == R.id.switch_btn) { // 切换摄像头
			cameraHelper.switchCamera();
		} else if (id == R.id.root_layout) {
			if (callingState == CallingState.NORMAL) {
				if (bottomContainer.getVisibility() == View.VISIBLE) {
					bottomContainer.setVisibility(View.GONE);
					topContainer.setVisibility(View.GONE);

				} else {
					bottomContainer.setVisibility(View.VISIBLE);
					topContainer.setVisibility(View.VISIBLE);

				}
			}
		}

	}

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

	}

	@Override
	public void onBackPressed() {

		super.onBackPressed();
		//moveTaskToBack(true);		
	}
/*	private void releaseRecorder() {
		if (mediaRecorder != null) {
			mediaRecorder.release();
			mediaRecorder = null;
		}
	}

	protected void releaseCamera() {
		try {
			if (mCamera != null) {
				mCamera.stopPreview();
				mCamera.release();
				mCamera = null;
			}
		} catch (Exception e) {
		}
	}*/
 /*   @Override
    // apk暂停时执行的动作：把相机关闭，避免占用导致其他应用无法使用相机
    protected void onPause() {
        super.onPause();

        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }

    @Override
    // 恢复apk时执行的动作
    protected void onResume() {
        super.onResume();
        if (null!=mCamera){
            mCamera = getCameraInstance();
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();
            } catch(IOException e) {
                Log.d(TAG, "Error setting camera preview: " + e.getMessage());
            }
        }
    }*/	
}
