package com.quyunshuo.module.home.utils

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.media.MediaPlayer.OnCompletionListener
import android.media.MediaPlayer.OnPreparedListener
import android.os.Build
import android.os.CountDownTimer
import android.util.Log
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import android.view.animation.AlphaAnimation
import androidx.annotation.RequiresApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class SimplePlayerUtil : OnPreparedListener, OnCompletionListener, MediaPlayer.OnErrorListener,
    SurfaceHolder.Callback {
    private var surface: Surface? = null
    private var textureView: TextureView? = null
    private var surfaceView: SurfaceView? = null
    private var url: String? = null
    private var onPreparedListener: OnPreparedListener? = null
    private var onCompletionListener: OnCompletionListener? = null
    private var onErrorListener: MediaPlayer.OnErrorListener? = null
    var player: MediaPlayer? = null
        private set
    var size: Float = 1f
    private var fadeInAnimation: AlphaAnimation? = null
    private var fadeOutAnimation: AlphaAnimation? = null

    //渐强的时长，单位：毫秒；默认2秒
    val duration: Long = 2000

    //音量调节的时间间隔1
    var interval: Long = duration / 10

    constructor(textureView: TextureView?) {
        this.textureView = textureView
        // 创建一个淡入动画，从完全透明到不透明
        fadeInAnimation = AlphaAnimation(0f, 1f)
        fadeInAnimation!!.duration = 500 // 设置动画时长为0.5秒

        // 创建一个淡出动画，从不透明到完全透明
        fadeOutAnimation = AlphaAnimation(1f, 0f)
        fadeOutAnimation!!.duration = 500 // 设置动画时长为0.5秒
        setup()
    }

    fun setVolume() {
        if (size <= 0) {
            player!!.setVolume(size, size)
            return
        }
        object : CountDownTimer(duration, interval) {
            override fun onTick(millisUntilFinished: Long) {
                val volume = 1f - millisUntilFinished * 1.0f / duration
                if (this@SimplePlayerUtil.player != null) {
                    player!!.setVolume(volume, volume)
                }
            }

            override fun onFinish() {
                if (this@SimplePlayerUtil.player != null) {
                    player!!.setVolume(1f, 1f)
                }
            }
        }.start()
    }

    constructor() {
        setup()
    }


    constructor(surfaceView: SurfaceView?) {
        this.surfaceView = surfaceView
        // 创建一个淡入动画，从完全透明到不透明
        fadeInAnimation = AlphaAnimation(0f, 1f)
        fadeInAnimation!!.duration = 500 // 设置动画时长为0.5秒

        // 创建一个淡出动画，从不透明到完全透明
        fadeOutAnimation = AlphaAnimation(1f, 0f)
        fadeOutAnimation!!.duration = 500 // 设置动画时长为0.5秒
        setup()
    }


    private fun setup() {
        player = MediaPlayer()
        if (textureView != null) {
            textureView!!.surfaceTextureListener = object : SurfaceTextureListener {
                override fun onSurfaceTextureAvailable(
                    surfaceTexture: SurfaceTexture,
                    i: Int,
                    i1: Int
                ) {
                    surface = Surface(surfaceTexture)
                    //                    textureView.setSurfaceTexture(surfaceTexture);
                    player!!.setSurface(surface)
                    Log.d(
                        TAG,
                        "iMediaPlayer1 onSurfaceTextureAvailable: $surface"
                    )
                }


                override fun onSurfaceTextureSizeChanged(
                    surfaceTexture: SurfaceTexture,
                    i: Int,
                    i1: Int
                ) {
                }


                override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean {
                    error = true
                    if (this@SimplePlayerUtil.player != null) {
                        //                        iMediaPlayer.reset();//进入闲置状态
                        player!!.release() //进入闲置状态后，进入 End (结束) 状态（涉及到资源的释放）,不能转换为其他状态
                        this@SimplePlayerUtil.player = null
                        Log.d(TAG, "iMediaPlayer2 onDestroy: ")
                    }
                    if (surface != null) {
                        surface!!.release()
                        surface = null
                    }
                    return true
                }


                override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {
                }
            }
        } else if (surfaceView != null) {
            surfaceView!!.holder.addCallback(this)
        }

        player!!.setOnPreparedListener(this)
        player!!.setOnCompletionListener(this)
        player!!.setOnErrorListener(this)
        //        iMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        //            @Override
        //            public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
        //                LogUtil.d(TAG,"onBufferingUpdate:"+i);
        //            }
        //        });
        //        iMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
        //            @Override
        //            public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
        //                LogUtil.d(TAG,"i:"+i+" -i1"+i1);
        //                return false;
        //            }
        //        });
    }

    var playPosition: Int = 0

    override fun onPrepared(mediaPlayer: MediaPlayer) {
        Log.d(TAG, fadeInAnimation.toString() + "onPrepared: " + surfaceView)
        if (surfaceView != null) {
            surfaceView!!.startAnimation(fadeInAnimation) // 淡入动画
        }
        if (textureView != null) {
            textureView!!.startAnimation(fadeInAnimation) // 淡入动画
        }

        // 准备就绪了，开始播放

//        if (getPlayPosition() != 0 && !"5121".equals(Hawk.get("logo",1))) {
//            int duration = mediaPlayer.getDuration();
//            Log.d(TAG, duration + ":playTime: " + getPlayPosition());
//            if (duration >= getPlayPosition()) {
//                iMediaPlayer.seekTo(getPlayPosition());
//            }
//        }
        player!!.start()

        playPosition = 0

        //        iMediaPlayer.setVolume(0,0);
        if (onPreparedListener != null) {
            onPreparedListener!!.onPrepared(player)
        }
    }


    private var error = false


    fun setUrl(url: String?) {
        this.url = url
        playVideo()
    }


    @SuppressLint("CheckResult")
    fun playVideo() {
        GlobalScope.launch {
            if (this@SimplePlayerUtil.player == null || error) {
                return@launch
            }
            try {
                if (!player!!.isPlaying) {
                    player!!.reset()
                    player!!.setDataSource(url)
                    player!!.prepareAsync()
                }
                /* if (iMediaPlayer.isPlaying()) {
                            error = false;
                            LogUtil.d(TAG, "isPlaying");
                            iMediaPlayer.stop();
                        }*/
            } catch (e: Exception) {
                Log.e(TAG, "异常$e")
                //playVideo();
                onError(null, 0, 0)
            }
        }

    }


    fun setError(error: Boolean) {
        this.error = error
    }


    fun onDestroy() {
        error = true
        Log.d(TAG, surface.toString() + "iMediaPlayer1 onDestroy: " + player)
        if (player != null) {
            if (player!!.isPlaying) {
                player!!.stop()
                Log.d(TAG, "onDestroy: ")
            }
            //            iMediaPlayer.reset();//进入闲置状态
            player!!.release() //进入闲置状态后，进入 End (结束) 状态（涉及到资源的释放）,不能转换为其他状态
            //            iMediaPlayer = null;
        }
        if (surface != null) {
            surface!!.release()
            surface = null
        }
    }

    fun snipping(): Bitmap? {
        if (textureView != null) {
            return textureView!!.bitmap
        }
        return null
    }


    fun setOnCompletionListener(onCompletionListener: OnCompletionListener?) {
        this.onCompletionListener = onCompletionListener
    }


    fun setOnErrorListener(onErrorListener: MediaPlayer.OnErrorListener?) {
        this.onErrorListener = onErrorListener
    }


    fun setOnPreparedListener(onPreparedListener: OnPreparedListener?) {
        this.onPreparedListener = onPreparedListener
    }


    override fun onCompletion(mediaPlayer: MediaPlayer) {
//        surfaceView.startAnimation(fadeOutAnimation); // 淡出动画
        if (surfaceView != null) {
            surfaceView!!.startAnimation(fadeInAnimation) // 淡入动画
        }
        if (textureView != null) {
            textureView!!.startAnimation(fadeOutAnimation) // 淡入动画
        }
        if (onCompletionListener != null) {
            onCompletionListener!!.onCompletion(player)
        } else {
            playVideo()
        }
    }


    override fun onError(mediaPlayer: MediaPlayer?, i: Int, i1: Int): Boolean {
        //        playVideo();
        if (onErrorListener != null) {
            return onErrorListener!!.onError(mediaPlayer, i, i1)
        }
        return true
    }

    fun stopVideo() {
        if (player != null) {
            if (player!!.isPlaying) {
                error = false
                player!!.stop()
            }
            player!!.reset()
        }
    }


    override fun surfaceCreated(holder: SurfaceHolder) {
        if (player != null) {
            player!!.setDisplay(holder)
        }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
    }


    override fun surfaceDestroyed(holder: SurfaceHolder) {
        error = true
        if (player != null) {
            player!!.reset() //进入闲置状态
            player!!.release() //进入闲置状态后，进入 End (结束) 状态（涉及到资源的释放）,不能转换为其他状态
            player = null
            surfaceView = null
            Log.d(TAG, "iMediaPlayer2 onDestroy: ")
        }
        Log.d(TAG, "iMediaPlayer2 onDestroy: ")
    }

    companion object {
        private const val TAG = "SimplePlayer"
    }
}