package com.yidianling.course.widget

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.ImageView
import com.alibaba.android.arouter.launcher.ARouter
import com.dou361.ijkplayer.widget.PlayStateParams
import com.dou361.ijkplayer.widget.PlayerView
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.interfaces.OnInvokeView
import com.ydl.media.audio.utils.PlayProgressUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.course.R
import com.yidianling.course.coursePlay.CoursePlayActivity
import com.yidianling.course.flutterPlugin.CourseSendPlugin
import com.yidianling.course.uitls.VideoProgressUtil
import java.util.*

/**
 * @author jiucheng
 * @描述:视频悬浮窗
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/11/19
 */
object VideoFloatHelper {
    private const val courseTag = "course_video_play"
    var courseVideoUrl = ""
    var courseId = ""
    var isCanClick = true
    var isCurrentVideoPlaying = true
    //视频播放器view
    @SuppressLint("StaticFieldLeak")
    private var videoView: PlayerView? = null
    private var timer: Timer? = null
    var defaultShowPattern = ShowPattern.CURRENT_ACTIVITY

    fun setVideoInfo(
        courseId: String,
        courseVideoUrl: String,
        isCanClick: Boolean
    ): VideoFloatHelper {
        this.courseId = courseId
        this.courseVideoUrl = courseVideoUrl
        this.isCanClick = isCanClick
        return this
    }


    fun showVideoFloat(activity: Activity) {
        val x = RxDeviceTool.getScreenWidth(activity) - RxImageTool.dp2px(220f)
        val y = RxDeviceTool.getScreenHeight(activity) * 3 / 4

        EasyFloat.with(activity)
            .setTag(courseTag)
            .setShowPattern(defaultShowPattern)
            .setLocation(x, y)
            .setAppFloatAnimator(null)
            .setFilter(CoursePlayActivity::class.java)
            .setLayout(R.layout.course_float_video_view, OnInvokeView {
                it.findViewById<ImageView>(R.id.iv_video_close).setOnClickListener {
                    dismissFloat(activity)
                }
                val videoFullScreen = it.findViewById<ImageView>(R.id.iv_video_full_screen)
                if (isCanClick) {
                    videoFullScreen.visibility = View.VISIBLE
                } else {
                    videoFullScreen.visibility = View.INVISIBLE
                }
                videoFullScreen.setOnClickListener {
                    if (isCanClick) {
                        startCoursePlayActivity(activity, 1, 1, courseVideoUrl, true)
                    }
                }

                val videoLayout = it.findViewById<ImageView>(R.id.app_video_box)

                try {
                    initVideoPlayer(activity, videoLayout)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            })
            .show()
    }

    private fun initVideoPlayer(activity: Activity, view: View) {
        val url = courseVideoUrl.replace("https", "http")
        val hisTime = PlayProgressUtil.getProgress(activity, url)
        videoView = PlayerView(activity, view)
            .setScaleType(PlayStateParams.fitparent)
            .hideAllUI()
            .setNetWorkTypeTie(false)
            .setAutoReConnect(true, 3)
            .forbidTouch(true)
            .setOnInfoListener { _, what, _ ->
                if (what == PlayStateParams.STATE_COMPLETED) {
                    isCurrentVideoPlaying = false
                    PlayProgressUtil.saveProgress(activity, url, 0)
                } else {
                    isCurrentVideoPlaying = true
                }

                true
            }
            .setPlaySource(url)
            .startPlay()
            .seekTo(hisTime)

        view.setOnClickListener {
            if (isCanClick) {
                startCoursePlayActivity(activity, 1, 0, courseVideoUrl, true)
            }
        }

        startTimer(url, activity)
    }


    private fun startTimer(url: String, activity: Activity) {
        if (timer == null) {
            timer = Timer()
        }
        timer?.schedule(object : TimerTask() {
            override fun run() {
                if (isCurrentVideoPlaying) {
                    var time = videoView?.currentPosition ?: 0
                    if (time < 3000) return
                    PlayProgressUtil.saveProgress(activity, url, time)
                }
            }
        }, 1000, 1000)
    }


    private fun startCoursePlayActivity(
        context: Context?,
        from: Int,
        fullScreen: Int,
        coursePlayUrl: String,
        isFromFloatView: Boolean
    ) {
        ARouter.getInstance()
            .build("/course/play")
            .withInt("course_id", courseId.toInt())
            .withInt("course_type", 1)
            .withString("coursePlayUrl", coursePlayUrl)
            .withInt("from", from)
            .withBoolean("isFromFloatView", isFromFloatView)
            .withInt("fullScreen", fullScreen)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            .navigation()
    }


    fun dismissFloat(activity: Activity) {
        CourseSendPlugin.sendMsg(false)
        EasyFloat.dismissAppFloat( courseTag)
        if (videoView != null) {
            videoView!!.stopPlay()
            videoView = null
        }
        if (timer != null) {
            timer!!.cancel()
        }
        timer = null
    }
}