package com.gh.download

import android.content.Context
import android.content.SharedPreferences
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.common.utils.toJsonIgnoredNull
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.core.utils.SPUtils

/**
 * 用来简单保存/获取下载时一些额外信息的辅助类，避免下载时反复修改原始下载实体的糟糕操作
 * 使用 SP 来实现，只适用于相对较为低频的调用
 */
object DownloadDataSimpleHelper {

    private val mSp: SharedPreferences by lazy {
        HaloApp.getInstance().getSharedPreferences("DownloadDataSimpleDao", Context.MODE_PRIVATE)
    }

    fun getDownloadDataSimpleEntity(url: String): DownloadDataSimpleEntity? {
        return mSp.getString(url, "")?.toObject()
    }

    fun updateDownloadDataSimpleEntity(
        url: String,
        downloadStartUpTime: Long? = null,
        downloadSpeedTime: Long? = null,
        downloadSpeedSize: Long? = null,
    ) {
        val entity = getDownloadDataSimpleEntity(url) ?: DownloadDataSimpleEntity()
        entity.downloadStartUpTime = downloadStartUpTime

        entity.downloadSpeedTime = downloadSpeedTime
        entity.downloadSpeedSize = downloadSpeedSize

        SPUtils.setString(mSp, url, entity.toJsonIgnoredNull())
    }

    fun updateDownloadSimpleEntityFirstTimeDownload(url: String, isFirstTimeDownload: Boolean) {
        val entity = getDownloadDataSimpleEntity(url) ?: DownloadDataSimpleEntity()

        entity.isFirstTimeDownload = isFirstTimeDownload

        SPUtils.setString(mSp, url, entity.toJsonIgnoredNull())
    }

    fun removeDownloadSimpleEntity(url: String) {
        SPUtils.remove(mSp, url)
    }

}

class DownloadDataSimpleEntity(
    var downloadStartUpTime: Long? = null,

    var downloadSpeedTime: Long? = null,
    var downloadSpeedSize: Long? = null,

    var isFirstTimeDownload: Boolean? = true
)