package com.quyunshuo.module.home.fragment.vm

import android.media.MediaPlayer
import android.media.MediaPlayer.OnCompletionListener
import android.os.Environment
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.BaseViewModel
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.util.FileUtil
import com.quyunshuo.module.home.fragment.repo.BuyFragmentRepo
import com.quyunshuo.module.home.utils.SimplePlayerUtil
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import java.io.File
import javax.inject.Inject

/**
 * HomeFragment 的 VM 层
 *
 * @author Qu Yunshuo
 * @since 2021/8/5 11:11 下午
 */
@HiltViewModel//@HiltViewModel 注解的作用是将 ViewModel 标记为可以由 Hilt 管理的依赖项。当你将 @HiltViewModel 注解添加到 ViewModel 类上时，Hilt 会自动处理 ViewModel 的创建和注入过程。这样，你就不需要手动调用 ViewModelProvider 来获取 ViewModel 实例了。
class BuyFragmentVM @Inject constructor(private val mRepo: BuyFragmentRepo) : BaseViewModel() {
    private val TAG = "BuyFragmentVM"
    private var simplePlayerUtil: SimplePlayerUtil? = null
    private var playVideos: ArrayList<File>? = null
    private var playVideoIndex: Int = 0;


    /**
     * 获得可以播放的视频(根据广告规则播放)
     */
    private fun getPlayVideos(): ArrayList<File> {
        var playVideos = ArrayList<File>()
        //获得可以播放的video
        val gson = Gson()

        //存储广告规则 ,用于前台播放。
        val playRules = SpUtils.getString(MMKVName.PLAY_RULE, "")
        if (playRules == "") {
            return playVideos
        }
        var list = gson.fromJson<ArrayList<String>>(
            playRules,
            object : TypeToken<ArrayList<String?>?>() {}.type
        )
        if (list.size < 1) {
            return playVideos
        }

        //1 本地的所有广告数据
        val allFiles = FileUtil.getAllFiles(
            Environment.getExternalStorageDirectory().path + "/adB/",
            ""
        )
        if (allFiles == null || allFiles.size < 1) {
            return playVideos
        }

        //创建一个可以播放的list
        allFiles.forEach {
            for ((index, s) in list.withIndex()) {
                if (it.name.split(".")[0] == s) {
                    playVideos.add(it)
                    Log.d(TAG, "getPlayVideos1: $playVideos")
                    break
                }
            }
        }

        Log.d(TAG, "getPlayVideos2: " + playVideos.size)
        return playVideos
    }

    /**
     * 获得可以播放的视频(读取本地文件)
     */
    private fun getPlayVideosLocal(): ArrayList<File> {
        var playVideos = ArrayList<File>()
        //获得可以播放的video
        val gson = Gson()

        //1 本地的所有广告数据
        val allFiles = FileUtil.getAllFiles(
            Environment.getExternalStorageDirectory().path + "/adB/",
            ""
        )
        if (allFiles == null || allFiles.size < 1) {
            return playVideos
        }

        //创建一个可以播放的list
        allFiles.forEach {
            playVideos.add(it)
            Log.d(TAG, "getPlayVideosLocal: $playVideos")
        }

        Log.d(TAG, "getPlayVideosLocal: " + playVideos.size)
        return playVideos
    }

    /**
     * 开始播放
     */
    fun playvideo(simplePlayerUtil: SimplePlayerUtil) {
        Log.d("backinfo","播放playvideo")
        playVideoIndex = 0
        //是否根据广告规则播放
        if (SpUtils.getBoolean(MMKVName.AD_RULE, true) == true) {
            Log.d("backinfo","getPlayVideos")

            playVideos = getPlayVideos()
        }else{
            playVideos = getPlayVideosLocal()
            Log.d("backinfo","getPlayVideosLocal")
        }

        this.simplePlayerUtil = simplePlayerUtil
        with(simplePlayerUtil) {
            setOnErrorListener { mp, what, extra ->
                Log.d(TAG, "onError: ")
                true
            }
            setOnCompletionListener {
                if (playVideoIndex >= playVideos!!.size) {
                    playVideoIndex = 0
                }
                Log.d(TAG, "onCompletion: " + playVideoIndex + ":" + playVideos!!.size)
                if (playVideos!!.size > 0) {
                    simplePlayerUtil.setUrl(playVideos!![playVideoIndex].absolutePath)
                    playVideoIndex++

                }
            }
            setOnPreparedListener { Log.d(TAG, "onPrepared: ") }
            Log.d("backinfo","playVideos!!.size："+playVideos!!.size)

            if (playVideos!!.size > 0) {
                Log.d(TAG, "playvideo: " + playVideos!!.size + "...." + playVideoIndex)
                Log.d(TAG, "initRequestData: " + playVideos!![playVideoIndex])
                simplePlayerUtil.setUrl(playVideos!![playVideoIndex].absolutePath)
                Log.d(TAG, "onCompletion: " + playVideoIndex + ":" + playVideos!!.size)
                playVideoIndex++
            }
        }
    }


}