package com.lianxin.pubqq.ulive;

import android.Manifest;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.chat.BaseLiveActivity;
import com.lianxin.panqq.chat.EMLiveCallHelper;
import com.lianxin.panqq.chat.EMLiveManager;
import com.lianxin.panqq.ulive.UControlView;
import com.lianxin.panqq.ulive.UMessageView;
import com.lianxin.panqq.ulive.UControlView.CtrlCallback;
import com.lianxin.panqq.chat.entity.EMLiveStateChangeListener;
import com.lianxin.panqq.chat.utils.CameraHelper;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.PermissionChecker;
import com.lianxin.panqq.common.Utils;

import android.media.MediaPlayer;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LearnWatchActivity extends BaseLiveActivity {
    public static final String TAG = LearnWatchActivity.class.getSimpleName();
    
	private SurfaceView localSurface;
	private SurfaceHolder localSurfaceHolder; 
	private static SurfaceView mainSurface;
	private SurfaceHolder mainSurfaceHolder;	
	EMLiveCallHelper callHelper;
	private CameraHelper cameraHelper;	
 
    FrameLayout flLoading;
 
    UMessageView mMessageView = null;     
    UControlView controlCenter = null;  
    TextView tvLoadingBuffer;
    private String mUri;
     
    private boolean mIsListViewOn = true;//是否显示弹幕  
 
    private  ProgressDialog progressDialog;   
    @Override
    protected void onCreate(Bundle bundles) {
        super.onCreate(bundles);
        setContentView(R.layout.live_activity_learnwatch);
  
        //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;
			}

		});       
        
        flLoading = (FrameLayout) findViewById(R.id.fl_loading);          

        mUri = getIntent().getStringExtra("videoPath");
        mPublishId = 1001;
        nLiveMode = 4; //3:主播  4:教学     
        //初始化发布者ID、观看者ID等        
        initLive();   
        //初始化视频窗口（主播窗口和学生头像）     
        initSurface();
        if(mPublishId>=1005){
        	postHanderMessage( MSG_LIVE_WATCH_LOCAL, mPublishId );       	          
        } 
       	//初始化状态指示
        initStateContainer();       
        //初始化弹幕
        initMessageView();        
        //必须此处初始化亮度、声音     
        initControlView();   
		// 设置直播监听
		addLiveStateListener();      
	    if(progressDialog!=null&&progressDialog.isShowing()){
         //   progressDialog.dismiss();
        }
    }
    
    protected void initSurface() {
        //if(mPublishId>=1005){   	
		// 显示本地图像的surfaceview
		localSurface = (SurfaceView) findViewById(R.id.local_surface);
		localSurface.setZOrderMediaOverlay(true);
		localSurface.setZOrderOnTop(true);
		localSurfaceHolder = localSurface.getHolder();
  
		localSurfaceHolder.addCallback(new localCallback());
        // 设置该SurfaceView自己不维护缓冲 		
		localSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);		
       // }
		mainSurface = (SurfaceView) findViewById(R.id.videoview);
		//mainSurface.setZOrderMediaOverlay(true);
		//mainSurface.setZOrderOnTop(true);
		mainSurfaceHolder = mainSurface.getHolder();		
		
		// 获取callHelper,cameraHelper//发送接口
		callHelper = EMLiveCallHelper.getInstance();
		callHelper.setSurfaceView(mPublishId,mainSurface);		
		//cameraHelper = new CameraHelper(callHelper, localSurfaceHolder);
		//    cameraHelper.setStartFlag(true);
        //cameraHelper.startCapture();  
        if(mPublishId<1005){
        	mainSurfaceHolder.addCallback(new localCallback());   
       		mainSurface.setVisibility(View.VISIBLE); 
       		mainSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);      		
    		cameraHelper = new CameraHelper(callHelper, mainSurfaceHolder);       		
            //   cameraHelper.setStartFlag(true);
            //cameraHelper.startCapture();
        }else{
    		//callHelper.setSurfaceView(mPublishId,mainSurface);        	
    		mainSurfaceHolder.addCallback(new oppositeCallback()); 
       		mainSurface.setVisibility(View.VISIBLE); 		
    		mainSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
    		cameraHelper = new CameraHelper(callHelper, localSurfaceHolder); 
    		//cameraHelper.setStartFlag(true);   		
       }
        cameraHelper.startCapture();       
    }

	private void initMessageView(){
    	if(mMessageView != null)
    		return;
    	mMessageView = (UMessageView)findViewById(R.id.message_view); 
    	//mMessageView.initMessageList();     	
    }    
 
	/**
	 * 本地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) {        		
    		mIsListViewOn = false;
  
    		mainSurface.setVisibility(View.VISIBLE);  			
			callHelper.onWindowResize(width, height, format);
			if (!cameraHelper.isStarted()) {
				if (!isInComingCall) {
						//EMCallManager.getInstance().makeVideoCall(userid);				
						// 通知cameraHelper可以写入数据
						cameraHelper.setStartFlag(true);
				}

			} else {
			}
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
		}

	}
	
	private TextView nickTextView;
	private TextView liveStateTextView;  	
	private Chronometer chronometer; 
	private LinearLayout liveStateContainer;
	//初始化状态指示
    protected void initStateContainer() {
  	
		liveStateTextView = (TextView) findViewById(R.id.tv_live_state);
		liveStateContainer = (LinearLayout) findViewById(R.id.ll_state_container);
	
		nickTextView = (TextView) findViewById(R.id.tv_nick);
		chronometer = (Chronometer) findViewById(R.id.chronometer);
	
		chronometer.setVisibility(View.VISIBLE);
		chronometer.setBase(SystemClock.elapsedRealtime());								
		// 开始记时
		chronometer.start();
		//nickTextView.setVisibility(View.INVISIBLE);
		nickTextView.setText(mRommName);		
    }
    //初始化弹幕显示窗口和输入窗口	
	
    private void initControlView() {
    	controlCenter = (UControlView) findViewById(R.id.control_center);
    	controlCenter.initVolumeWithLight(LearnWatchActivity.this);    		
    	controlCenter.registerCallback(new CtrlCallback(){	
    		//双击事件，有的视频播放器支持双击播放暂停，可从这实现
			@Override
			public void onDoubleClick(int val) {
            	if(mIsListViewOn){
            		//listView.setVisibility(View.GONE);	
            		mMessageView.setVisibility(View.GONE);            		
            		mIsListViewOn = false;
            	}else{
            		//listView.setVisibility(View.VISIBLE); 
            		mMessageView.setVisibility(View.VISIBLE);            		
            		mIsListViewOn = true;
            	}		
			}
			@Override
			public void onBrightnessChange(int val) {
				WindowManager.LayoutParams lp = getWindow().getAttributes();
		        lp.screenBrightness = val / 255f;
		        getWindow().setAttributes(lp);				
				controlCenter.setVisibility(View.VISIBLE);
			}
			@Override
			public void onVolumeChange(int val) {
				controlCenter.setVisibility(View.VISIBLE);
			}
			@Override
			public void onShowControlView(boolean val) {
				if(val){
					controlCenter.setVisibility(View.VISIBLE);	
				}else{
					controlCenter.setVisibility(View.GONE);					
				}
				
			}
		});    	
    }    
 
    // 触摸事件进行监听
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        /*if (mGestureDetector != null)
            mGestureDetector.onTouchEvent(event);*/
        if (controlCenter != null)
        	controlCenter.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        flLoading.setVisibility(View.VISIBLE);
      /*  if (mVideoView.isPlaying())
        	mVideoView.pause();*/
        tvLoadingBuffer.setText("直播已缓冲" + percent + "%...");
    }

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

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		//moveTaskToBack(true);		
	}   
    
	//设置直播状态监听
	void addLiveStateListener() {
		EMLiveManager.getInstance().addLiveStateChangeListener(		
				new EMLiveStateChangeListener() {
					@Override					
				    public void onError(int errorCode, String errorMessage) {
						final String str = errorMessage;
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								liveStateTextView.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;								
								liveStateTextView.setText(str);
							}
						});
				    }					
					@Override
					public void onLiveStateChanged(LiveState callState,
							LiveError error) {
	

					}
					
					@Override
					public void onUserTextCome(int userid, String message) {
						mMessageView.insertMesaage( userid, message );
					}

					@Override
					public void onUserCustomCome(int userid, byte[] data,
								int length) {
						String str = "自己去定义";						
						mMessageView.insertMesaage( userid, str );
					}
					
					@Override
					public void onUserJoinRoom(int userid, String status) {
						String str = "自己（"+ userid + "）进入了";					
						mMessageView.insertMesaage( 10000, str );
					}

					@Override
					public void onUserExitRoom(int userid, String status) {
						String str = "自己（"+ userid + "）退出了";					
						mMessageView.insertMesaage( 10000, str );
					}					
				});
	}
}
