package com.sunzee.utils;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sunzee.base.BaseApplication;
import com.sunzee.ui.activity.AdvertisingActivity;
import com.wuxiaolong.androidutils.library.LogUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 视频图片播放工具类
 */
public class SimplePlayerUtils implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
    private SurfaceView mSurfaceView;
    private ImageView mImageView;
    private Surface surface;
    private static final String TAG = "SimplePlayer";
    private SurfaceHolder holder;
    private MediaPlayer iMediaPlayer;

    private List<File> urlLinkedList = new ArrayList<>();
    private int index;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private static String mPath;
    private final MyHandler mHandler;

    public SimplePlayerUtils(SurfaceView surfaceView) {
        this.mSurfaceView = surfaceView;
        mHandler = new MyHandler();
        LogUtil.d(TAG, "setup: " + mHandler);
        setup();
    }

    public void CloseVolume() {
        iMediaPlayer.setVolume(0, 0);
    }

    public void setImageView(ImageView imageView) {
        mImageView = imageView;
    }

    private void setup() {
        iMediaPlayer = new MediaPlayer();
        LogUtil.d(TAG, "setup: " + iMediaPlayer);
        if (mSurfaceView != null) {
            holder = mSurfaceView.getHolder();
            holder.addCallback(new SimplePlayerUtils.SimplayerCallBack());
        }
        iMediaPlayer.setOnPreparedListener(this);
        iMediaPlayer.setOnCompletionListener(this);
        iMediaPlayer.setOnErrorListener(this);

    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        iMediaPlayer.start();
    }

    private boolean error = false;


    public void setFileData(List<File> list) {
        urlLinkedList.clear();
        urlLinkedList.addAll(list);
        index = 0;
    }

    @SuppressLint("CheckResult")
    public void playVideo() {
        LogUtil.d(TAG, "vpplayVideo: " + index);
        mPath = urlLinkedList.get(index).getAbsolutePath();
        String[] format = mPath.split("\\.");
        if (format[1].equals("mp4")) {
            mHandler.sendEmptyMessage(1);
            try {
                Flowable.just(mPath)
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(Schedulers.io())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String first) throws Exception {
                                if (iMediaPlayer == null || error) {
                                    return;
                                }
                                LogUtil.d(TAG, "播放视频：" + first);
                                try {
                                    if (iMediaPlayer.isPlaying()) {
                                        error = false;
                                        LogUtil.d(TAG + "accepti", "isPlaying");
                                        iMediaPlayer.stop();
                                    }
                                    iMediaPlayer.reset();
                                    iMediaPlayer.setDataSource(first);
                                    iMediaPlayer.prepareAsync();
                                } catch (Exception e) {
                                    if (index == 0) {
                                        index = 0;
                                    } else {
                                        index--;
                                    }
                                    e.printStackTrace();
                                    LogUtil.e(TAG, "异常" + e.toString());
                                    onError(null, 0, 0);
                                }
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.e(TAG, "异常 -1：" + e.toString());
            }
        } else if (format[1].equals("png")) {
            //为视频还没播放完就结束了，所以我们需要这关闭视频。否则回出现问题的
            mHandler.sendEmptyMessage(2);
            if (iMediaPlayer.isPlaying()) {
                error = false;
                LogUtil.d(TAG + "accepti", "isPlaying");
                iMediaPlayer.stop();
            }
            iMediaPlayer.reset();
            startPlayImg();
        }

    }

    public void onDestroy() {
        LogUtil.d(TAG + "i", "onDestroy");
        error = true;
        if (iMediaPlayer != null) {
            iMediaPlayer.release();
            iMediaPlayer.setOnCompletionListener(null);
            iMediaPlayer.setOnErrorListener(null);
            iMediaPlayer.setOnPreparedListener(null);
            iMediaPlayer = null;
        }
        if (surface != null) {
            surface.release();
            surface = null;
        }
        stopPlayImg(mTimer, mTimerTask);
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        LogUtil.d(TAG, "onCompletion" + urlLinkedList.size() + ",index:" + index + " mediaPlayer.isPlaying()" + mediaPlayer.isPlaying());
        index++;
        if (index >= urlLinkedList.size()) {
            index = 0;
        }
        playVideo();
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        LogUtil.d(TAG, "onError first:" + i + " second:" + i1);
        playVideo();
        return true;
    }

    public class SimplayerCallBack implements SurfaceHolder.Callback {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if (iMediaPlayer != null) {
                iMediaPlayer.setDisplay(holder);
            }
        }

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


        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        }
    }

    /**
     * 开始播放图片inde
     */
    private void startPlayImg() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimer != null && mTimerTask != null) {
            mTimerTask.cancel();
        }
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                //继续播放视频
                index++;
                LogUtil.d(TAG, "run: " + urlLinkedList.size());
                if (index >= urlLinkedList.size()) {
                    index = 0;
                }
                playVideo();

            }
        };

        //播放10秒
        mTimer.schedule(mTimerTask, 1000 * 10);
    }

    /**
     * 停止播放图片
     */
    private void stopPlayImg(Timer timer, TimerTask task) {
        if (timer != null) {
            task.cancel();
            timer.purge();
            timer.cancel();
            timer = null;
            task = null;
        }
    }

    public class MyHandler extends Handler {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    mImageView.setVisibility(View.GONE);
                    mSurfaceView.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    mImageView.setVisibility(View.VISIBLE);
                    mSurfaceView.setVisibility(View.GONE);
                    Glide.with(BaseApplication.getContext())
                            .load(mPath)
                            .apply(new RequestOptions().override((int) DensityUtil.dp2px(960), (int) DensityUtil.dp2px(1080)))
                            .into(mImageView);
                    break;
            }
        }
    }
}