package com.hc.sysvideo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hc.sysvideo.bean.IVideoInfo;
import com.hc.sysvideo.listener.OnVideoControlListener;
import com.hc.sysvideo.listener.SimplePlayerCallback;
import com.hc.sysvideo.utils.NetworkUtils;
import com.hc.sysvideo.view.VideoBehaviorView;
import com.hc.sysvideo.view.VideoControllerView;
import com.hc.sysvideo.view.VideoProgressOverlay;
import com.hc.sysvideo.view.VideoSystemOverlay;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 视频播放器View
 */
public class BDVideoView extends VideoBehaviorView {

    private SurfaceView mSurfaceView;
    private View mLoading;
    private ImageView animLoading;
    private VideoControllerView mediaController;
    private VideoSystemOverlay videoSystemOverlay;
    private VideoProgressOverlay videoProgressOverlay;
    private BDVideoPlayer mMediaPlayer;
    private BdPlayerListener bdPlayerListener;
    private View seekContainer;
    private SeekBar seekBar;
    TextView percentText;

    //延迟滑动计时器
    private Timer timer ;
    private TimerTask timerTask;

    //页面activity
    Activity mainActivity;

    private int initWidth;
    private int initHeight;

    private boolean isPrepared = false;     //当前视频是否已经加载完毕
    private long currentTime = 0;           //记录滑动的时间点

    private String TAG = " BDVideoView";

    public boolean isLock() {
        return mediaController.isLock();
    }

    public BDVideoView(Context context) {
        super(context);
        init();
    }

    public BDVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BDVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void setBdPlayerListener(BdPlayerListener listener){
        this.bdPlayerListener = listener;
    }

    private void init() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        inflater.inflate(R.layout.video_view, this);

        mSurfaceView = findViewById(R.id.video_surface);
        mLoading = findViewById(R.id.video_loading);
        animLoading = findViewById(R.id.loading_anim);
        mediaController = findViewById(R.id.video_controller);
        videoSystemOverlay = findViewById(R.id.video_system_overlay);
        videoProgressOverlay = findViewById(R.id.video_progress_overlay);
        seekContainer = findViewById(R.id.seek_container_show);
        seekBar = findViewById(R.id.seek_bar_tv);
        percentText = findViewById(R.id.percent_text);

        seekBar.setMax(1000);
        seekBar.setProgress(0);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int mProgress = 0;
                if (fromUser) {
                    mProgress = progress;
                }
                percentText.setText(mProgress/10 + "%");

                if(progress<=0){
                    seekBar.setProgress(10);
                    percentText.setText("1%");
                }

                if(progress >= 1000){
                    seekBar.setProgress(990);
                    percentText.setText("99%");
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        initLoadingAnimation();
        initPlayer();

        mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                initWidth = getWidth();
                initHeight = getHeight();

                if (mMediaPlayer != null) {
                    mMediaPlayer.setDisplay(holder);
                    mMediaPlayer.openVideo();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });

        registerNetChangedReceiver();
    }


    private void initLoadingAnimation(){
        animLoading.setImageResource(R.drawable.loading_animation);
        AnimationDrawable a = (AnimationDrawable)animLoading.getDrawable();
        a.start();
    }

    private void initPlayer() {
        mMediaPlayer = new BDVideoPlayer();
        mMediaPlayer.setCallback(new SimplePlayerCallback() {

            @Override
            public void onStateChanged(int curState) {
                switch (curState) {
                    case BDVideoPlayer.STATE_IDLE:
                        am.abandonAudioFocus(null);
                        break;
                    case BDVideoPlayer.STATE_PREPARING:
                        am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
                        break;
                }
            }

            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaController.updatePausePlay();
                bdPlayerListener.onComplete();
            }

            @Override
            public void onError(MediaPlayer mp, int what, int extra) {
                mediaController.checkShowError(false);
            }

            @Override
            public void onLoadingChanged(boolean isShow) {
                if (isShow) showLoading();
                else hideLoading();
            }

            @Override
            public void onPrepared(MediaPlayer mp) {
                mMediaPlayer.start();
                mediaController.show();
                mediaController.hideErrorView();
                isPrepared = true;
            }
        });
        mediaController.setMediaPlayer(mMediaPlayer);
    }

    /**
     * 获取当前播放进度
     * by xuling 20190726
     */
    public int getCurrentPositionWhenPlaying() {
        int position = 0;
        if (isPrepared) {
            try {
                position = mMediaPlayer.getCurrentPosition();
            } catch (Exception e) {
                e.printStackTrace();
                return position;
            }
        }
        return position;
    }

   /*
     * 播放/暂停
     * by xuling 20180726
     */
    public void playOrPause(){
        if(!isPrepared){
            return;
        }
        if(mMediaPlayer.isPlaying()){
            mMediaPlayer.pause();
            mediaController.show();
        }else{
            mMediaPlayer.start();
        }
    }

   /**//**
     * 获取当前视频时长(毫秒)
     * by xuling 20180726
     */
    public int getDuration(){
        if(!isPrepared){
            return 0;
        }
        return mMediaPlayer.getDuration();

    }

    /**//**
     * 当前能否滑动
     * by xuling 20180726
     */
    public boolean canSeek(){
        return isPrepared;
    }


    /*
     * 左右滑动
     * by xuling 20180726
     */
    public void seek(int position){
        if(!isPrepared){
            return;
        }

        seekContainer.setVisibility(VISIBLE);
        seekBar.setProgress(position);

        currentTime =Calendar.getInstance().getTimeInMillis();
        cancelTimer();
        initTimer();
    }

    /*
     * 传递activity实例
     * by xuling 20180726
     */
    public void setActivity(Activity activity){
        this.mainActivity = activity;
    }

    /*
     * 延迟执行视频快进任务
     * by xuling 20180726
     */
    private void initTimer(){
        if(mainActivity == null){
            Log.d(TAG,"请向播放器传递activity实例");
            return;
        }
        if(timer == null){
            timer = new Timer();
        }
        timerTask = new TimerTask() {
            @Override
            public void run() {
                mainActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        long myCurrentTime = Calendar.getInstance().getTimeInMillis();
                        if(myCurrentTime - currentTime > 3){
                            int position = seekBar.getProgress();
                            position = position* getDuration()/1000;
                            seekTo(position);
                            seekContainer.setVisibility(INVISIBLE);
                        }
                    }
                });
            }
        };

        timer.schedule(timerTask,3000);
    }

    /* 跳转
     * by xuling 20180726
     */
    private void seekTo(int position){
        mMediaPlayer.seekTo(position);
    }

    /*
     * 取消延迟执行视频快进任务
     * by xuling 20180726
     */
    private void cancelTimer(){
        if(timerTask != null){
            timerTask.cancel();
        }
    }

    /*
 * 播放
 * by xuling 20180726
 */
    public void play(){
        if(!isPrepared){
            return;
        }
        if(!mMediaPlayer.isPlaying()){
            mMediaPlayer.start();
        }
    }

    /*
   * 暂停
   * by xuling 20180726
   */
    public void pause(){
        if(!isPrepared){
            return;
        }
        if(mMediaPlayer.isPlaying()){
            mMediaPlayer.pause();
        }
    }

    private void showLoading() {
        mLoading.setVisibility(View.VISIBLE);
    }

    private void hideLoading() {
        mLoading.setVisibility(View.GONE);
    }

    private boolean isBackgroundPause;

    public void onStop() {
        if (mMediaPlayer.isPlaying()) {
            // 如果已经开始且在播放，则暂停同时记录状态
            isBackgroundPause = true;
            mMediaPlayer.pause();
        }
    }

    public void onStart() {
        if (isBackgroundPause) {
            // 如果切换到后台暂停，后又切回来，则继续播放
            isBackgroundPause = false;
            mMediaPlayer.start();
        }
    }

    public void onDestroy() {
        mMediaPlayer.stop();
        mediaController.release();
        unRegisterNetChangedReceiver();

       /* if(timer !=null){
            timer.cancel();
        }
        if(timerTask !=null){
            timerTask.cancel();
        }
        timer = null;
        timerTask = null;

        mSurfaceView = null;
        mLoading = null;
        animLoading = null;
        mediaController = null;
        videoSystemOverlay = null;
        videoProgressOverlay = null;
        mMediaPlayer = null;
        bdPlayerListener = null;
        seekContainer = null;
        seekBar = null;*/
    }

    /**
     * 开始播放
     */
    public void startPlayVideo(final IVideoInfo video) {
        if (video == null) {
            return;
        }

        mMediaPlayer.reset();

        String videoPath = video.getVideoPath();
        mediaController.setVideoInfo(video);
        mMediaPlayer.setVideoPath(videoPath);
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        mediaController.toggleDisplay();
        return super.onSingleTapUp(e);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        if (isLock()) {
            return false;
        }
        return super.onDown(e);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if (isLock()) {
            return false;
        }
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    @Override
    protected void endGesture(int behaviorType) {
        switch (behaviorType) {
            case VideoBehaviorView.FINGER_BEHAVIOR_BRIGHTNESS:
            case VideoBehaviorView.FINGER_BEHAVIOR_VOLUME:
                Log.i("DDD", "endGesture: left right");
                videoSystemOverlay.hide();
                break;
            case VideoBehaviorView.FINGER_BEHAVIOR_PROGRESS:
                Log.i("DDD", "endGesture: bottom");
                mMediaPlayer.seekTo(videoProgressOverlay.getTargetProgress());
                videoProgressOverlay.hide();
                break;
        }
    }

    @Override
    protected void updateSeekUI(int delProgress) {
        videoProgressOverlay.show(delProgress, mMediaPlayer.getCurrentPosition(), mMediaPlayer.getDuration());
    }

    @Override
    protected void updateVolumeUI(int max, int progress) {
        videoSystemOverlay.show(VideoSystemOverlay.SystemType.VOLUME, max, progress);
    }

    @Override
    protected void updateLightUI(int max, int progress) {
        videoSystemOverlay.show(VideoSystemOverlay.SystemType.BRIGHTNESS, max, progress);
    }

    public void setOnVideoControlListener(OnVideoControlListener onVideoControlListener) {
        mediaController.setOnVideoControlListener(onVideoControlListener);
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            getLayoutParams().width = initWidth;
            getLayoutParams().height = initHeight;
        } else {
            getLayoutParams().width = FrameLayout.LayoutParams.MATCH_PARENT;
            getLayoutParams().height = FrameLayout.LayoutParams.MATCH_PARENT;
        }

    }

    private NetChangedReceiver netChangedReceiver;

    public void registerNetChangedReceiver() {
        if (netChangedReceiver == null) {
            netChangedReceiver = new NetChangedReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            activity.registerReceiver(netChangedReceiver, filter);
        }
    }

    public void unRegisterNetChangedReceiver() {
        if (netChangedReceiver != null) {
            activity.unregisterReceiver(netChangedReceiver);
        }
    }

    private class NetChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Parcelable extra = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (extra != null && extra instanceof NetworkInfo) {
                NetworkInfo netInfo = (NetworkInfo) extra;

                if (NetworkUtils.isNetworkConnected(context) && netInfo.getState() != NetworkInfo.State.CONNECTED) {
                    // 网络连接的情况下只处理连接完成状态
                    return;
                }

                mediaController.checkShowError(true);
            }
        }
    }

    public interface BdPlayerListener{
        public void onComplete();
    }
}
