package com.lianxin.pubqq.ulive;

import android.Manifest;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.chat.EMLiveCallHelper;
import com.lianxin.panqq.chat.EMLiveManager;
import com.lianxin.panqq.ulive.preference.Settings;
import com.lianxin.panqq.ulive.preference.ULiveStreaming;
import com.lianxin.panqq.ulive.UControlView;
import com.lianxin.panqq.ulive.UControlView.CtrlCallback;
import com.lianxin.panqq.ulive.UMessageView;
import com.lianxin.panqq.chat.BaseLiveActivity;
import com.lianxin.panqq.chat.entity.EMLiveStateChangeListener;
import com.lianxin.panqq.chat.utils.CameraHelper;
import com.lianxin.panqq.client.askLiveClient;
import com.lianxin.panqq.client.callback.getCallBack;
import com.lianxin.panqq.common.DefineUser;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.PermissionChecker;
import com.lianxin.panqq.common.Utils;

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


    public static final int MSG_UPDATE_COUNTDOWN = 1;
    public static final int MSG_UPDATE_COUNTTIME = 2;
    
    public static final int COUNTDOWN_DELAY = 1000;

    public static final  int COUNTDOWN_START_INDEX = 3;
    public static final  int COUNTDOWN_END_INDEX = 1;


    protected Settings mSettings;

    //protected String rtmpPushStreamDomain = "publish3.cdn.ucloud.com.cn";

    //Views
    protected ImageView mCameraToggleIv;
    protected ImageView mLampToggleIv;
    protected ImageButton mCloseRecorderImgBtn;
    protected ImageButton mToggleFilterImgBtn;
    protected Button mBackImgBtn;
    protected Button mEndImgBtn;   
    protected Button mDebugImgBtn; 
    protected Button mWebImgBtn;
    protected Button mLocalImgBtn; 
    protected Button mFollowImgBtn;    
//    protected View mFocusIndex;
//    protected TextView mBitrateTxtv;
    protected TextView mCountDownTxtv;
    protected TextView mRecordedTimeTxtv;
    protected TextView mOutputStreamInfoTxtv;
    protected TextView mBufferOverfloInfoTxtv;
  //  protected ViewGroup mContainer;
    protected ViewGroup mWelContainer;
    protected ViewGroup mEndContainer;
    protected ViewGroup mButContainer;
    
    //protected UAspectFrameLayout mPreviewContainer;

    protected boolean isShutDownCountdown = false;
    protected boolean isStopCountTime = false; 
    
    protected ULiveStreaming mLiveStreaming;

    protected UiHandler uiHandler;
    UMessageView mMessageView = null;     
    UControlView controlCenter = null;  
    private boolean mIsListViewOn = false;//是否显示弹幕    

    
	SurfaceView surFaceView = null;
	private SurfaceHolder surFaceHolder;  
	EMLiveCallHelper callHelper;
	private CameraHelper cameraHelper; 
    @Override
    protected void onCreate(Bundle bundles) {
        super.onCreate(bundles);
  
        setContentView(R.layout.live_layout_live_room_view);
        
        //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;
			}

		});        
        
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mSettings = new Settings(this);
        if (mSettings.getVideoCaptureOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        nLiveMode = 3; //3:主播  4:教学  
        initLive(); //初始化发布者ID、观看者ID等       
        init();
        //startPlay();
        //initSurface();      
      
    }

    private void init() {
    	//设置计数器，到时间后initSurface();
        uiHandler = new UiHandler(getMainLooper());
        //初始化控件
        initView();
        //初始化弹幕
        initMessageView(); 
        //初始化亮度、声音及其他控制
        initControlView(); 
		// 设置通话监听
		addLiveStateListener();        
    }
 
    private class UiHandler extends Handler {
        public UiHandler(Looper looper) {
            super(looper);
        }
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_COUNTDOWN:
                    handleUpdateCountdown(msg.arg1);
                    break;
            }
        }
    }    
    
    private void initSurface() {
    	if(surFaceView != null)  //已经初始化过了
    		return;
		// 显示本地图像的surfaceview
    	surFaceView = (SurfaceView) findViewById(R.id.local_surface);
		//localSurface.setZOrderMediaOverlay(true);
		//localSurface.setZOrderOnTop(true);
		surFaceHolder = surFaceView.getHolder();

		// 获取callHelper,cameraHelper//发送接口
		callHelper = EMLiveCallHelper.getInstance();
		cameraHelper = new CameraHelper(callHelper, surFaceHolder);  
		surFaceHolder.addCallback(new localCallback());
        // 设置该SurfaceView自己不维护缓冲 		
		surFaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);		
        
       // cameraHelper.setStartFlag(true);
        cameraHelper.startCapture(); 
    }
 
	private void initMessageView(){
    	if(mMessageView != null)
    		return;
    	mMessageView = (UMessageView)findViewById(R.id.message_view); 
    	//mMessageView.initMessageList();     	
    }    

 
    private void initControlView() {
    	controlCenter = (UControlView) findViewById(R.id.control_center);
    	controlCenter.initVolumeWithLight(LivePublishActivity.this);    		
    	controlCenter.registerCallback(new CtrlCallback(){	
    		//双击事件，有的视频播放器支持双击播放暂停，可从这实现
			@Override
			public void onDoubleClick(int val) {
            	if(mIsListViewOn){
            		mButContainer.setVisibility(View.VISIBLE);	
            		mMessageView.setVisibility(View.GONE);            		
            		mIsListViewOn = false;
            	}else{
            		mButContainer.setVisibility(View.GONE); 
            		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);					
				}
				
			}
		});    	
    }    
 
    /**
     * 触摸事件进行监听
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
 
        if (controlCenter != null)
        	controlCenter.onTouchEvent(event);
        return super.onTouchEvent(event);
    }    
    
    private void startPlay() {
        new Thread(){
            public void run() {
                int i = COUNTDOWN_START_INDEX;
                do {
                    try {
                        Thread.sleep(COUNTDOWN_DELAY);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message msg = Message.obtain();
                    msg.what = MSG_UPDATE_COUNTDOWN;
                    msg.arg1 = i;
                    uiHandler.sendMessage(msg);
                    i--;
                }while(i >= COUNTDOWN_END_INDEX);
            }
        }.start();
   //     progressDialog.dismiss();
//        initViewChat();
 //       cameraHelper.setStartFlag(true);      
       // startCount(); 
       // initControlView();  
      
    } 
 
    private Runnable mTicker;  
    long startTime = 0;    
    private void startCount() {
        // 清零 开始计时
    	mRecordedTimeTxtv.setText("00:00:00");
        //stepTimeHandler = new Handler();
        startTime = System.currentTimeMillis();    	
    	mTicker = new Runnable() {
            public void run() {
            	if(isStopCountTime) 
            		return;
                String content = showTimeCount(System.currentTimeMillis() - startTime);
                mRecordedTimeTxtv.setText(content);
                String str = "发送"+GloableParams.n_MediaSendCount+" 接收"+GloableParams.n_MediaRecvCount;								
                mOutputStreamInfoTxtv.setText(str); 
                /*long now = SystemClock.uptimeMillis();
                long next = now + (1000 - now % 1000);
                stepTimeHandler.postAtTime(mTicker, next);*/
                if(!isStopCountTime)
                uiHandler.postDelayed(this, 1000);               
            }
        };
        //启动计时线程，定时更新
        mTicker.run();
    }
    
    public String showTimeCount(long time) {
        if(time >= 360000000){
            return "00:00:00";
        }
        String timeCount = "";
        long hourc = time/3600000;
        String hour = "0" + hourc;
        hour = hour.substring(hour.length()-2, hour.length());
       
        long minuec = (time-hourc*3600000)/(60000);
        String minue = "0" + minuec;
        minue = minue.substring(minue.length()-2, minue.length());
       
        long secc = (time-hourc*3600000-minuec*60000)/1000;
        String sec = "0" + secc;
        sec = sec.substring(sec.length()-2, sec.length());
        timeCount = hour + ":" + minue + ":" + sec;
        return timeCount;
    }    
	/**
	 * 本地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) {
		}
	} 

    public void handleUpdateCountdown(final int count) {
        if (mCountDownTxtv != null) {
            mCountDownTxtv.setVisibility(View.VISIBLE);
            mCountDownTxtv.setText(String.format("%d", count));
            ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f,0f, 1.0f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            scaleAnimation.setDuration(COUNTDOWN_DELAY);
            scaleAnimation.setFillAfter(false);
            scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mCountDownTxtv.setVisibility(View.GONE);

                    if (count == COUNTDOWN_END_INDEX && mLiveStreaming != null && !isShutDownCountdown) {
                        mLiveStreaming.startRecording();
                                                
                    }
                    if (mRecordedTimeTxtv != null) {
                        mRecordedTimeTxtv.setVisibility(View.VISIBLE);
                      //  long time = Long.valueOf(event.toString());
                      //  String retVal = StringUtil.getTimeFormatString(time);
                      //  mRecordedTimeTxtv.setText(retVal);
                        cameraHelper.setStartFlag(true);                       
                        startCount();                       
                    } 
                    if (mOutputStreamInfoTxtv != null) {
                    	mOutputStreamInfoTxtv.setVisibility(View.VISIBLE);
                    }
                    if (mBufferOverfloInfoTxtv != null) {
                    	mBufferOverfloInfoTxtv.setVisibility(View.VISIBLE);
                    }                    
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            if (!isShutDownCountdown) {
                mCountDownTxtv.startAnimation(scaleAnimation);
            } else {
                mCountDownTxtv.setVisibility(View.GONE);
            }
        }
    }	

    private void initView() {
        mCameraToggleIv = (ImageView) findViewById(R.id.img_bt_switch_camera);
        mLampToggleIv = (ImageView) findViewById(R.id.img_bt_lamp);
        mCloseRecorderImgBtn = (ImageButton) findViewById(R.id.img_bt_close_record);
       // mFocusIndex = findViewById(R.id.focus_index);
        //mBitrateTxtv = (TextView) findViewById(R.id.bitrate_txtv);
        //mPreviewContainer = (UAspectFrameLayout)findViewById(R.id.container);
        mCountDownTxtv = (TextView) findViewById(R.id.countdown_txtv);
        mRecordedTimeTxtv = (TextView) findViewById(R.id.recorded_time_txtv);
        mOutputStreamInfoTxtv = (TextView) findViewById(R.id.output_url_txtv);
        mToggleFilterImgBtn = (ImageButton) findViewById(R.id.img_bt_filter);
        mBufferOverfloInfoTxtv = (TextView) findViewById(R.id.network_overflow_count);
        mEndImgBtn = (Button) findViewById(R.id.btn_finish);
        mBackImgBtn = (Button) findViewById(R.id.btn_return);        
        mDebugImgBtn = (Button) findViewById(R.id.btn_debug);
        mWebImgBtn = (Button) findViewById(R.id.btn_web);
        mFollowImgBtn = (Button) findViewById(R.id.btn_follow); 
        mLocalImgBtn = (Button) findViewById(R.id.btn_Local);       
        //mContainer = (ViewGroup) findViewById(R.id.live_finish_container);
        mEndContainer = (ViewGroup) findViewById(R.id.live_finish_container);       
        mWelContainer = (ViewGroup) findViewById(R.id.live_welcome_container);   
        mButContainer = (ViewGroup) findViewById(R.id.live_bottom_container);
        
        mEndContainer.setVisibility(View.INVISIBLE);        
        mCameraToggleIv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mLiveStreaming != null) {
                    //mLiveStreaming.switchCamera();
                }
                cameraHelper.switchCamera();               
            }
        });
        mLampToggleIv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mLiveStreaming != null) {
                    mLiveStreaming.toggleFlashMode();
                }               
            }

        });
        mCloseRecorderImgBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                isShutDownCountdown = true;
                isStopCountTime = true;                
                mCloseRecorderImgBtn.setEnabled(false);
                if (mLiveStreaming != null) {
                    mLiveStreaming.stopRecording();
                }
                mEndContainer.setVisibility(View.VISIBLE);
            }
        });
        mToggleFilterImgBtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
               // if (BasePublishDemo.this instanceof PublishDemo4MediaCodec) {            	
                if (true) {
                    mLiveStreaming.toggleFilter();
                } else {
                    Toast.makeText(LivePublishActivity.this, "Sorry, just support for mediacodec.", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mDebugImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	//startPlay();           	
            	initSurface();
            	//mWelContainer.setVisibility(View.INVISIBLE); 
            	//surFaceView.setVisibility(View.VISIBLE);             	
            }
        });
 
        mLocalImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	startPlay();           	
            	initSurface();           	
            	mWelContainer.setVisibility(View.INVISIBLE); 
            	surFaceView.setVisibility(View.VISIBLE);  
            	postHanderMessage( MSG_LIVE_PUBLISH_LOCAL, 10000 );
            	//initControlView();          	
            }
        });        
        
        mWebImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	Utils.showLongToast(LivePublishActivity.this, "目前还没有准备好转发直播的网站服务器!");             	
            }
        });
        
        mFollowImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	//initSurface();
            	//mWelContainer.setVisibility(View.INVISIBLE); 
            	//surFaceView.setVisibility(View.VISIBLE);  
            	askLivePublish();            	
            }
        });        
        
        mBackImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //finish();
                Utils.finish(LivePublishActivity.this);               
            }
        }); 
        mEndImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //finish();
                Utils.finish(LivePublishActivity.this);               
            }
        }); 
               
    }

	@Override
	protected void onDestroy() {
		
		stHandler.sendEmptyMessage(MSG_LIVE_PUBLISH_END);
        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);		
	}   
    
	/**
	 * 设置直播状态监听
	 */
	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() {
							//	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 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( userid, str );
					}

					@Override
					public void onUserExitRoom(int userid, String status) {
						String str = "用户（"+ userid + "）退出了";					
						mMessageView.insertMesaage( userid, str );
					}					
				});
	} 
    
	private void askLivePublish(){
		int nUserId = GloableParams.m_szUserId;
		int nOursId	= nUserId;	
		if(TextUtils.isEmpty(GloableParams.m_szServerIp)){//判断是否已经登录服务器
			Utils.showLongToast(LivePublishActivity.this, "你还没有登录服务器!");
			return;
		}		
		getLoadingDialog("正在请求连接...").show();	
		askLiveClient.askLivePublish(DefineUser.TYPE_FRIEND,nUserId,new getCallBack(){	
			@Override
			public void onSuccess(int statusCode, byte[] recvBuf) {
				runOnUiThread(new Runnable() {
					public void run() {
						getLoadingDialog("正在请求连接...").dismiss();					
		            	initSurface();
		            	mWelContainer.setVisibility(View.INVISIBLE); 
		            	surFaceView.setVisibility(View.VISIBLE); 	
					}
				});				
			}
			@Override
			public void onFailure(int statusCode,  String message) {
				//getLoadingDialog("正在刷新数据...").dismiss();
				final String str = message;
				runOnUiThread(new Runnable() {
					public void run() {
						getLoadingDialog("正在请求连接...").dismiss();						
						Utils.showLongToast(LivePublishActivity.this, str);
					}
				});	
			}
		});	 			
	}
		
}
