package com.gh.common.videolog

import android.annotation.SuppressLint
import android.app.Application
import android.database.sqlite.SQLiteFullException
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.common.utils.toastInInternalRelease
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.room.AppDatabase
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import java.util.concurrent.ExecutorService

object VideoRecordUtils {
    private const val STORE_SIZE = 20
    private lateinit var mApplication: Application

    private val videoRecordSet by lazy { hashSetOf<VideoRecordEntity>() }
    private var videoRecordExecutor: ExecutorService? = null
    private val videoRecordDao by lazy { AppDatabase.getInstance().videoRecordDao() }

    @JvmStatic
    fun init(application: Application, executor: ExecutorService) {
        mApplication = application

        videoRecordExecutor = executor
        videoRecordExecutor?.execute {
            tryWithDefaultCatch {
                val recordList = videoRecordDao.getAll()
                videoRecordSet.addAll(recordList)
            }
        }
    }

    fun log(videoId: String) {
        videoRecordExecutor?.execute {
            try {
                val entity = VideoRecordEntity(videoId = videoId, time = System.currentTimeMillis() / 1000L)
                videoRecordSet.add(entity)
                videoRecordDao.insert(entity)
            } catch (e: Exception) {
                e.printStackTrace()
                if (e is SQLiteFullException) {
                    toastInInternalRelease("数据库/磁盘已满，写入视频新日志失败")
                }
            }
            if (videoRecordSet.size >= STORE_SIZE) {
                commitVideoRecord()
            }
        }
    }

    fun commitVideoRecord() {
        if (videoRecordSet.isEmpty() || !::mApplication.isInitialized) return
        videoRecordExecutor?.execute {
            uploadVideoRecord()
            val exposureList = videoRecordSet.toList()
            videoRecordSet.removeAll(exposureList)
            try {
                videoRecordDao.deleteMany(exposureList)
            } catch (e: SQLiteFullException) {
                toastInInternalRelease("数据库/磁盘已满，删除视频日志失败")
            }
        }
    }

    @SuppressLint("CheckResult")
    fun uploadVideoRecord(time: Long = 0) {
        if (!UserManager.getInstance().isLoggedIn) return
        val requestMap = HashMap<String, Any>()
        val videoIds = videoRecordSet.toList().map { it.videoId }
        requestMap["g_id"] = HaloApp.getInstance().gid ?: ""
        requestMap["time"] = time
        requestMap["video_id"] = videoIds
        RetrofitManager.getInstance().api
            .uploadVideoLog(requestMap.toRequestBody())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                }
            })
    }
}