package com.lianxin.pubqq.ulive;

import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.lianxin.pubqq.R;
import com.lianxin.pubqq.chat.VideoCallActivity;
import com.lianxin.panqq.chat.BasePhoneActivity;
import com.lianxin.panqq.chat.EMPhoneManager;
import com.lianxin.panqq.chat.entity.EMCallStateChangeListener;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.Utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
//import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class VoicePhoneActivity extends BasePhoneActivity implements OnClickListener {
    public static final String TAG = VoicePhoneActivity.class.getSimpleName();

	RelativeLayout controlCenter;
	RelativeLayout buttonsLay;	
    ImageView ivControlImg;	
    TextView tvControlName; 
    TextView tvControl;    

	private Button refuseBtn;
	private Button answerBtn;
	private Button hangupBtn;
	private ImageView muteImage;
	//private ImageView switchbtn;	
	private ImageView handsFreeImage;
	private TextView nickTextView;
	private TextView callStateTextView;
	private Chronometer chronometer;
	private LinearLayout voiceContronlLayout;
	private LinearLayout comingBtnContainer;
	private LinearLayout topContainer;
	private LinearLayout bottomContainer;	

	private boolean isMuteState;
	private boolean isHandsfreeState;
	private boolean isAnswered;
	private int streamID;
	private boolean endCallTriggerByMe = false;
	private Handler handler = new Handler();	
    private boolean mIsButsViewOn = true;//是否为全屏   
    //private int nDestId = 10003;    

    @Override
    protected void onCreate(Bundle bundles) {
        super.onCreate(bundles);
        setContentView(R.layout.live_activity_voicephone);

		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);        
       /* ivControlImg = (ImageView) findViewById(R.id.iv_control_img); 
        tvControlName = (TextView) findViewById(R.id.tv_control_name); 
        tvControl = (TextView) findViewById(R.id.tv_control);*/       
        controlCenter = (RelativeLayout) findViewById(R.id.control_center); 
        buttonsLay = (RelativeLayout) findViewById(R.id.lay_btns);        

        initPhone();
 
		initButtons();
		//initSurface();
		initTouchListener();
		// 设置通话监听
		addCallStateListener();	
	//	oppositeSurface.setVisibility(View.VISIBLE);		
		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);
			Uri ringUri = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
			audioManager.setMode(AudioManager.MODE_RINGTONE);
			audioManager.setSpeakerphoneOn(true);
			ringtone = RingtoneManager.getRingtone(this, ringUri);
			ringtone.play();
		}
		//cameraHelper.setStartFlag(true);		
    }
    
    protected void initButtons() {
		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);
		nickTextView = (TextView) findViewById(R.id.tv_nick);
		chronometer = (Chronometer) findViewById(R.id.chronometer);
		voiceContronlLayout = (LinearLayout) findViewById(R.id.ll_voice_control);
		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);	
    } 
    
 
    protected void initTouchListener() {
        ivControlImg = (ImageView) findViewById(R.id.iv_control_img); 
        tvControlName = (TextView) findViewById(R.id.tv_control_name); 
        tvControl = (TextView) findViewById(R.id.tv_control);  
        controlCenter = (RelativeLayout) findViewById(R.id.control_center);   	
        // 保持 屏幕常亮
   //     mVideoView.setKeepScreenOn(true);
  //      mPresenter.getPresenterPhoneLiveVideoInfo(Room_id);
  //      svProgressHUD = new SVProgressHUD(this);
        //获取屏幕宽度
  //      Pair<Integer, Integer> screenPair = ScreenResolution.getResolution(this);
  //      mScreenWidth = screenPair.first;
//   初始化声音和亮度
        initVolumeWithLight();
        //        添加手势监听
        addTouchListener();          
    }     

    /**
     * 音量   亮度
     *
     * @return
     */
    private int mScreenWidth = 0;//屏幕宽度
    private boolean mIsFullScreen = true;//是否为全屏
    private int mShowVolume;//声音
    private int mShowLightness;//亮度
    private int mMaxVolume;//最大声音
    private AudioManager mAudioManager;
    private GestureDetector mGestureDetector;
    private GestureDetector.SimpleOnGestureListener mSimpleOnGestureListener;
    /**
     * 声音
     */
    public final static int ADD_FLAG = 1;
    /**
     * 亮度
     */
    public final static int SUB_FLAG = -1;

    public static final int HIDE_CONTROL_BAR = 0x02;//隐藏控制条
    public static final int HIDE_TIME = 5000;//隐藏控制条时间
    public static final int SHOW_CENTER_CONTROL = 0x03;//显示中间控制
    public static final int SHOW_CONTROL_TIME = 1000;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                /**
                 *  隐藏top ,bottom
                 */
                case HIDE_CONTROL_BAR:

                    break;
                /**
                 *  隐藏center控件
                 */
                case SHOW_CENTER_CONTROL:
                    if (controlCenter != null) {
                        controlCenter.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };


 /*   protected int getLayoutId() {
//        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
 //       Vitamio.isInitialized(this);
//        return R.layout.activity_phonelive_video;
    	return 0;
    }

    protected void initView() {
  
    }*/

    /**
     * 初始化声音和亮度
     */
    private void initVolumeWithLight() {
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mShowVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 100 / mMaxVolume;
        mShowLightness = getScreenBrightness();
    }

    /**
     * 获得当前屏幕亮度值 0--255
     */
    private int getScreenBrightness() {
        int screenBrightness = 255;
        try {
         //   screenBrightness = Settings.System.getInt(getContentResolver(),
         //           Settings.System.SCREEN_BRIGHTNESS);
            screenBrightness = 200;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenBrightness;
    }

    protected void onEvent() {
        //        添加手势监听
        addTouchListener();
    }
    /**
     * 触摸事件进行监听
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector != null)
            mGestureDetector.onTouchEvent(event);

        return super.onTouchEvent(event);
    }

    /**
     * 添加手势操作
     */
    private void addTouchListener() {
        mSimpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
            //滑动操作
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                    float distanceX, float distanceY) {
                if (!mIsFullScreen)//非全屏不进行手势操作
                    return false;

                float x1 = e1.getX();

                float absDistanceX = Math.abs(distanceX);// distanceX < 0 从左到右
                float absDistanceY = Math.abs(distanceY);// distanceY < 0 从上到下

                // Y方向的距离比X方向的大，即 上下 滑动
                if (absDistanceX < absDistanceY) {
                    if (distanceY > 0) {//向上滑动
                        if (x1 >= mScreenWidth * 0.65) {//右边调节声音
                            changeVolume(ADD_FLAG);
                        } else {//调节亮度
                            changeLightness(ADD_FLAG);
                        }
                    } else {//向下滑动
                        if (x1 >= mScreenWidth * 0.65) {
                            changeVolume(SUB_FLAG);
                        } else {
                            changeLightness(SUB_FLAG);
                        }
                    }
                } else {
                    // X方向的距离比Y方向的大，即 左右 滑动
                    if (distanceX > 0) {//向上滑动
                          //调节亮度
                            changeLightness(ADD_FLAG);
                    } else {//向下滑动
                    	changeLightness(SUB_FLAG);
 
                    }
                }
                return false;
            }

            //双击事件，有的视频播放器支持双击播放暂停，可从这实现
            @Override
            public boolean onDoubleTap(MotionEvent e) {
            	if(mIsButsViewOn){
            		buttonsLay.setVisibility(View.GONE);	
            		mIsButsViewOn = false;
            	}else{
            		buttonsLay.setVisibility(View.VISIBLE);  
            		mIsButsViewOn = true;
            	}
                return super.onDoubleTap(e);
            }

            //单击事件
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
 
                return true;
            }
        };
        mGestureDetector = new GestureDetector(VoicePhoneActivity.this, mSimpleOnGestureListener);
    }

    /**
     * 改变声音
     */
    private void changeVolume(int flag) {
        mShowVolume += flag;
        if (mShowVolume > 100) {
            mShowVolume = 100;
        } else if (mShowVolume < 0) {
            mShowVolume = 0;
        }
        tvControlName.setText("音量");
        ivControlImg.setImageResource(R.drawable.img_volume);
        tvControl.setText(mShowVolume + "%");
        int tagVolume = mShowVolume * mMaxVolume / 100;
        //tagVolume:音量绝对值
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, tagVolume, 0);
        mHandler.removeMessages(SHOW_CENTER_CONTROL);
        controlCenter.setVisibility(View.VISIBLE);
        mHandler.sendEmptyMessageDelayed(SHOW_CENTER_CONTROL, SHOW_CONTROL_TIME);
    }

    /**
     * 改变亮度
     */
    private void changeLightness(int flag) {
        mShowLightness += flag;
        if (mShowLightness > 255) {
            mShowLightness = 255;
        } else if (mShowLightness <= 0) {
            mShowLightness = 0;
        }
        tvControlName.setText("亮度");
        ivControlImg.setImageResource(R.drawable.img_light);
        tvControl.setText(mShowLightness * 100 / 255 + "%");
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = mShowLightness / 255f;
        getWindow().setAttributes(lp);

        mHandler.removeMessages(SHOW_CENTER_CONTROL);
        controlCenter.setVisibility(View.VISIBLE);
        mHandler.sendEmptyMessageDelayed(SHOW_CENTER_CONTROL, SHOW_CONTROL_TIME);
    }

	/**
	 * 设置通话状态监听
	 */
	void addCallStateListener() {
		EMPhoneManager.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_AudioSendCount+" 接收"+GloableParams.n_AudioRecvCount;								
								callStateTextView.setText(str);
							}
						});
				    }					
					@Override
					public void onCallStateChanged(CallState callState,
							CallError error) {
						// Message msg = handler.obtainMessage();
						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: // 电话接通成功
						
							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());
									//oppositeSurface.setVisibility(View.VISIBLE);									
									// 开始记时
									chronometer.start();
									nickTextView.setVisibility(View.INVISIBLE);
									String st5 = getResources().getString(
											R.string.In_the_call);
									callStateTextView.setText(st5);
									callingState = CallingState.NORMAL;
									
								}

							});
							break;
						case ASKACCEPTED: // 对方请求发送
							
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									try {
										if (soundPool != null)
											soundPool.stop(streamID);
									} catch (Exception e) {
									}
									openSpeakerOn();

									comingBtnContainer.setVisibility(View.INVISIBLE);
									hangupBtn.setVisibility(View.VISIBLE);
									voiceContronlLayout.setVisibility(View.VISIBLE);
									//localSurface.setVisibility(View.VISIBLE);
									//oppositeSurface.setVisibility(View.VISIBLE);			
									if (ringtone != null)
										ringtone.stop();

									//if (!isInComingCall) {			
									//if (true) {
										try {
											isAnswered = true;
											//EMPhoneManager.getInstance().answerCall(2);					
										//	cameraHelper.setStartFlag(true);
									//cameraHelper.startCapture();											
									//GloableParams.n_MediaSendCount = 1000;
											openSpeakerOn();
											handsFreeImage.setImageResource(R.drawable.icon_speaker_on);
											isHandsfreeState = true;
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
											//saveCallRecord(1);
											//finish();
										}
									//}									
								}

							});
							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(VoicePhoneActivity.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();

			stHandler.sendEmptyMessage(MSG_CALL_REJECT_VOICE);
			callingState = CallingState.REFUESD;
		} else if (id == R.id.btn_answer_call) { // 接听电话
			comingBtnContainer.setVisibility(View.INVISIBLE);
			hangupBtn.setVisibility(View.VISIBLE);
			voiceContronlLayout.setVisibility(View.VISIBLE);
			if (ringtone != null)
				ringtone.stop();

			if (isInComingCall) {
				//if (true) {
				try {
					isAnswered = true;
					EMPhoneManager.getInstance().answerCall(1);
					//cameraHelper.setStartFlag(true);

					openSpeakerOn();
					handsFreeImage.setImageResource(R.drawable.icon_speaker_on);
					isHandsfreeState = 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_VOICE);
			callDruationText = chronometer.getText().toString();
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
			}
			//finish();
			Utils.finish(VoicePhoneActivity.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;
			}
			//case R.id.switch_btn: // 切换摄像头
			//	cameraHelper.switchCamera();
			//	break;
		} 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_VOICE);	

		super.onDestroy();        
	}

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