package com.lianxin.pubqq.ulive;

import android.Manifest;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lianxin.pubqq.R;
//import com.lianxin.pubqq.chat.PermissionChecker;
import com.lianxin.panqq.ulive.UMessageView;
import com.lianxin.panqq.ulive.USurfaceMainView;
import com.lianxin.panqq.ulive.USurfaceMainView.MainCallback;
import com.lianxin.panqq.ulive.widget.URotateSurfaceView;
import com.lianxin.panqq.chat.BaseLiveActivity;
import com.lianxin.panqq.chat.EMLiveCallHelper;
import com.lianxin.panqq.chat.EMLiveManager;
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;

public class LiveWatchActivity extends BaseLiveActivity {
    public static final String TAG = LiveWatchActivity.class.getSimpleName();

    private SurfaceView surFaceView = null;
	private SurfaceHolder surFaceHolder;  
	private EMLiveCallHelper callHelper;
	private CameraHelper cameraHelper; 
   // private String mUri;
    protected int pagesize = 20;
    private  ProgressDialog progressDialog;
    private  USurfaceMainView mSurfaceMainView;  

    URotateSurfaceView mRotateView;
    UMessageView mMessageView = null; 
    private boolean mIsListViewOn = false;//是否显示弹幕     
    @Override
    protected void onCreate(Bundle bundles) {
        super.onCreate(bundles);
        setContentView(R.layout.live_activity_liveplay);
        //mPublishId = getIntent().getIntExtra("Publish_ID", 1000);
        //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;
			}

		});        
        mSurfaceMainView = (USurfaceMainView)findViewById(R.id.video_main_view);         
        mRotateView = (URotateSurfaceView) mSurfaceMainView.findViewById(R.id.videoview); 
        mSurfaceMainView.initProgressView();  //必须此处初始化亮度、声音   
        //mSurfaceMainView.initSurface();  //必须此处初始化亮度、声音    
        
        nLiveMode = 3; //3:主播  4:教学 
        initLive(); //初始化发布者ID、观看者ID等     
       // mPublishId = 1001;  
    	//初始化状态指示
        initStateContainer();         
        initSurface();  //初始化视频窗口       
        if(mPublishId>=1005){
        	postHanderMessage( MSG_LIVE_WATCH_LOCAL, mPublishId );       	
            /*progressDialog=new ProgressDialog(this);
            progressDialog.setMessage("正在进入直播间...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();  */          
        } 
       
        //初始化弹幕
        initMessageView();  
		// 设置直播监听
		addLiveStateListener();	        
        mSurfaceMainView.registerCallback(new MainCallback(){	
    		@Override
			public void onPlayButtonClick(boolean isplay) {
    		//	cameraHelper.setStartFlag(isplay);    			
    			initMessageView();	
			}
			@Override
			public void onBrightnessButtonClick(boolean isshow) {

			}
			@Override
			public void onPlayDoubleClick(boolean isshow) {
            	if(isshow){
            		mMessageView.setVisibility(View.VISIBLE); 	
            	}else{
            		mMessageView.setVisibility(View.GONE);
            	}
			}
		});       
  
    }

    public void initSurface() {
    	
		// 显示本地图像的surfaceview
    	surFaceView = mSurfaceMainView.getSurfaceView();
		surFaceHolder = surFaceView.getHolder();
	    // 设置该SurfaceView自己不维护缓冲 		
		surFaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);	
		// 获取callHelper,cameraHelper//发送接口
		callHelper = EMLiveCallHelper.getInstance();
		callHelper.setSurfaceView(mPublishId,surFaceView); 		
		cameraHelper = new CameraHelper(callHelper, surFaceHolder);  

 	
        //initView();
        if(mPublishId<1005){
    		surFaceHolder.addCallback(new localCallback());       	
            //   cameraHelper.setStartFlag(true);
            //cameraHelper.startCapture();
        }else{
    		//callHelper.setSurfaceView(mPublishId,surFaceView);        	
    		surFaceHolder.addCallback(new oppositeCallback());      	
        }
    }    
    
	/**
	 * 本地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);
			//surFaceView.setVisibility(View.VISIBLE);			
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			callHelper.onWindowResize(width, height, format);
			if (!cameraHelper.isStarted()) {
				/*if (!isInComingCall) {
						EMCallManager.getInstance().makeVideoCall(userid);
						cameraHelper.setStartFlag(true);
				}*/
				//EMPhoneManager.getInstance().setCallId(userid,playid,calltime);
			} else {
				surFaceView.setVisibility(View.VISIBLE);				
			}
			surFaceView.setVisibility(View.VISIBLE);			
		}

		@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 initMessageView(){
    	if(mMessageView != null)
    		return;
    	mMessageView = (UMessageView)findViewById(R.id.message_view); 
    	//mMessageView.initMessageList();     	
    }
	
	private void sendCustomMessage(){
        //此处实现自定义消息、礼物入口
    	byte[] dataBuf = new byte[64];
    	int length = 64;   			
    	sendCustomMessage( dataBuf, length ); 
		String str = "自己定义消息";					
		mMessageView.insertMesaage( 10000, str );    	
    } 
	
    @Override
    protected void onPause() {
        super.onPause();
  
    }


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

}
