package com.yidianling.course.coursePlay

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.PowerManager
import android.view.View
import android.widget.RelativeLayout
import com.dou361.ijkplayer.widget.PlayStateParams
import com.dou361.ijkplayer.widget.PlayerView
import com.ydl.media.audio.utils.PlayProgressUtil
import com.ydl.media.view.PlayTypeEnum
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.course.R
import com.yidianling.course.bean.CourseExtraBean
import com.yidianling.course.bean.CourseMediaBean
import tv.danmaku.ijk.media.player.IMediaPlayer
import java.text.SimpleDateFormat
import java.util.*


/**
 * 课程播放器的item
 * Created by harvie on 2017/6/26 0026.
 */
class CoursePlayItemViewVideo : RelativeLayout, PlayViewInterface {
    //播放列表
    private var playList: ArrayList<CourseMediaBean> = ArrayList()
    private var courseExtra: CourseExtraBean? = null
    var activity: CoursePlayActivity? = null

    var videoUrl: String? = null

    //播放模式
    var playMoudle = 0 //默认为0 音频播放  1视频播放

    var timer = Timer()

    var index = 0
    private var isVideoPlaying = true
    private var mHandler = Handler()
    var hasEnsureNetStatus = false

    private val formatter = SimpleDateFormat("mm:ss", Locale.getDefault())
    private var wakeLock: PowerManager.WakeLock? = null

    companion object {
        fun create(activity: CoursePlayActivity, playType: Int): CoursePlayItemViewVideo {
            return CoursePlayItemViewVideo(activity, playType)
        }
    }

    @SuppressLint("InvalidWakeLockTag")
    private constructor(context: CoursePlayActivity, playMoudle: Int) : super(context) {
        this.playMoudle = playMoudle
        View.inflate(context, R.layout.course_view_course_play_item, this)
        activity = context
        initView()

        wakeLock = (activity!!.getSystemService(Context.POWER_SERVICE) as PowerManager)
                .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ON_AFTER_RELEASE, "CoursePlayItemViewVideo")
    }

    override fun onNewIntent() {
    }

    fun initView() {
        findViewById<View>(R.id.simple_player_settings_container).visibility = View.GONE
        findViewById<View>(R.id.app_video_center_box).visibility = View.GONE //
        setListener()
        //开启定时器实时记录播放位置
        startTimer()
    }

    private fun startTimer() {
        timer?.schedule(object : TimerTask() {
            override fun run() {
                if (isVideoPlaying) {
                    var time = activity?.videoView?.currentPosition ?: 0
                    if (time < 3000) return
                    PlayProgressUtil.saveProgress(context, videoUrl, time)
                }
            }
        }, 1000, 1000)
    }


    //设置监听事件
    private fun setListener() {
    }


    private fun playNext() {
//        var size: Int = playList.size
//        if ((size - 1) > bean?.attachmentIndex ?: 0) {
//            //这里请勿给index先赋值，判断可播放后会自动赋值
//            val index = bean?.attachmentIndex ?: 0
//            play(index!! + 1, true)
//            UtilH.saveProgress(activity, playList[index].playUrl, 0);
//        }
    }

    override fun onResume() {
        if (wakeLock != null) {
            wakeLock!!.acquire()
        }
        activity?.videoView?.onResume()
        var hisTime1 = PlayProgressUtil.getProgress(context, videoUrl)
        activity?.videoView?.seekTo(hisTime1)
    }


    override fun onPause() {
        if (wakeLock != null) {
            if (wakeLock!!.isHeld) {
                wakeLock!!.release()
            }
        }
    }

    /**
     * 播放音频
     * index 播放下标
     */
    fun play(index: Int) {
        this.index = index
        var canPlay = false
        //判断当前课程是否试听
        if (playList[index].isDemo) {
            canPlay = true
        } else {
            //非试听
            if (courseExtra!!.isBuy) {
                //已购买
                canPlay = true
            } else {
                //未购买，判断是否是试听课程
                //即未购买，也不是试听，弹窗提示
                CommonDialog(activity)
                        .setMessage("\n购买课程，获取完整课程内容\n")
                        .setLeftOnclick("放弃") {

                        }
                        .setRightClick("购买") {
                            //跳转支付页
                            activity?.addCourseOrder()
                        }
                        .setCancelAble(false)
                        .show()
            }
        }
        if (canPlay) {
            PlayerFloatHelper.playingType=PlayTypeEnum.PLAY_TYPE_COURSE


            var url = playList[index].url
            url = url.replace("https", "http")

            videoUrl = url

            var hisTime = PlayProgressUtil.getProgress(context, url)
            try {
                activity?.videoView = PlayerView(activity)
                        .setScaleType(PlayStateParams.fitparent)
                        .hideMenu(true)
                        .hideRotation(true)
                        .setNetWorkTypeTie(!hasEnsureNetStatus)
                        .hideBack(true)
                        .hideSteam(true)
                        .setAutoReConnect(true, 3)
                        .forbidTouch(false)
                        .setOnInfoListener(object : IMediaPlayer.OnInfoListener {
                            override fun onInfo(mp: IMediaPlayer, what: Int, extra: Int): Boolean {

                                if (what == PlayStateParams.STATE_PAUSED) {
                                    this@CoursePlayItemViewVideo.findViewById<View>(R.id.rl_play_pause_layout).visibility = View.VISIBLE
                                } else {
                                    this@CoursePlayItemViewVideo.findViewById<View>(R.id.rl_play_pause_layout).visibility = View.GONE
                                }

                                if (what == PlayStateParams.STATE_PLAYING) {
                                    this@CoursePlayItemViewVideo.findViewById<View>(R.id.app_video_loading).visibility = View.GONE
                                }
                                if (what == PlayStateParams.MEDIA_INFO_BUFFERING_END
                                        || what == PlayStateParams.MEDIA_INFO_AUDIO_RENDERING_START
                                        || what == PlayStateParams.MEDIA_INFO_VIDEO_RENDERING_START
                                        || what == PlayStateParams.STATE_PLAYING
                                ) {
                                    activity?.isVideoPlay = true
                                    this@CoursePlayItemViewVideo.findViewById<View>(R.id.ll_bg).visibility = View.GONE
                                } else {
                                    mHandler.postDelayed({
                                        this@CoursePlayItemViewVideo.findViewById<View>(R.id.ll_bg).visibility = View.VISIBLE
                                    }, 550)
                                }

                                if (what == PlayStateParams.STATE_COMPLETED) {
                                    isVideoPlaying = false
                                    PlayProgressUtil.saveProgress(this@CoursePlayItemViewVideo.activity, videoUrl, 0)
                                    if (playList.size - 1 > this@CoursePlayItemViewVideo.index) {
                                        //播放下一曲
                                        play(this@CoursePlayItemViewVideo.index + 1)
                                        activity!!.updatePlayingListStatus(this@CoursePlayItemViewVideo.index)
                                    }
                                } else {
                                    isVideoPlaying = true
                                }
                                return true
                            }
                        })
                        .showThumbnail { ivThumbnail ->
                            run {
                                ivThumbnail.alpha = 0.5f
                                GlideApp.with(context)
                                        .load(courseExtra!!.pic)
                                        .into(ivThumbnail)
                            }
                        }
                        .setPlaySource(url)
                        .startPlay()
                        .seekTo(hisTime)
                val layout = activity?.window?.attributes
                layout?.screenBrightness = -1f
                activity?.window?.attributes = layout

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 设置显示数据
     */
    override fun setData(index: Int, list: ArrayList<CourseMediaBean>, courseExtra: CourseExtraBean, from: Int) {

        if (list.isEmpty()) return
        playList.clear()
        playList.addAll(list)
        this.courseExtra = courseExtra
        play(index)
    }

    override fun onDestroy() {
        timer.cancel()
    }
}