package com.doverfuelingsolutions.issp.bugly

import android.content.Context
import android.content.Intent
import com.doverfuelingsolutions.issp.DFSApplication
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.utils.AppUtil
import com.doverfuelingsolutions.issp.utils.DFSToastUtil
import com.doverfuelingsolutions.issp.view.UpgradeActivity
import com.tencent.bugly.Bugly
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.beta.UpgradeInfo
import com.tencent.bugly.beta.upgrade.UpgradeListener
import com.tencent.bugly.beta.upgrade.UpgradeStateListener
import com.tencent.bugly.crashreport.CrashReport

object BuglyUtil : UpgradeListener, UpgradeStateListener {

    override fun onUpgrade(ret: Int, upgradeInfo: UpgradeInfo?, isManual: Boolean, isSilence: Boolean) {
        if (upgradeInfo == null) {
            DFSToastUtil.info(R.string.no_update_version)
            return
        }

        Intent(DFSApplication.instance.applicationContext, UpgradeActivity::class.java).let {
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            DFSApplication.instance.applicationContext.startActivity(it)
        }
    }

    override fun onUpgradeNoVersion(isManual: Boolean) = DFSToastUtil.info(R.string.current_version_is_latest)
    override fun onUpgradeFailed(isManual: Boolean) = DFSToastUtil.info(R.string.download_fail)
    override fun onUpgrading(isManual: Boolean) {}
    override fun onDownloadCompleted(isManual: Boolean) {}
    override fun onUpgradeSuccess(isManual: Boolean) {}

    fun init(applicationContext: Context) {
        Beta.autoInit = true
        Beta.autoInstallApk = true
        Beta.autoCheckUpgrade = false
        Beta.upgradeCheckPeriod = 5 * 60_000
        Beta.upgradeListener = this
        val appId = if (AppUtil.isDebug()) "789ca54e1f" else "7bb19916d9"
        Bugly.init(applicationContext, appId, AppUtil.isDebug())

    }

    fun checkUpgrade() {
        Beta.checkUpgrade()
    }
}