package com.swago.app

import android.app.Application
import android.content.Context
import android.net.http.HttpResponseCache
import androidx.fragment.app.FragmentActivity
import androidx.multidex.MultiDex
import com.alibaba.android.arouter.launcher.ARouter
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.dialog.ForceOfflineDialog
import com.swago.baseswago.util.ActivityManagerUtil
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.UserInfo
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.TUIKitImpl
import com.tencent.qcloud.tim.uikit.base.IMEventListener
import com.tencent.qcloud.tim.uikit.config.TUIKitConfigs
import com.zy.multistatepage.MultiStateConfig
import com.zy.multistatepage.MultiStatePage
import java.io.File

/**
 *@date 2021/7/17 10:05
 *description:
 */
class SwagoApp : Application() {

    override fun onCreate() {
        super.onCreate()
        AppContext.setContext(this)
        if (BuildConfig.DEBUG) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        //firebase
        UserInfo.getLoginModel()?.let {
            Firebase.analytics.setUserId(it.user_account)
            Firebase.crashlytics.setUserId(it.user_account)
        }
        Firebase.crashlytics.setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG)
        CrashHandler.getInstance().init(this)
        ActivityManagerUtil.get().init(this)
        ARouter.init(this)
        TUIKit.init(this,UrlConstant.imId, TUIKitConfigs.getConfigs())
        //svga缓存
        val cacheDir = File(this.cacheDir, "http")
        HttpResponseCache.install(cacheDir, 1024 * 1024 * 128)

        val config = MultiStateConfig.Builder()
            .alphaDuration(300)
            .errorIcon(R.mipmap.state_error_empty)
            .emptyIcon(R.mipmap.state_error_empty)
            .emptyMsg("There is nothing here")
            .loadingMsg("")
            .errorMsg("Load data error")
            .build()
        MultiStatePage.config(config)

        TUIKitImpl.addIMEventListener(object:IMEventListener(){
            override fun onForceOffline() {
                super.onForceOffline()
                val currentActivity = ActivityManagerUtil.get().currentActivity()
                if (currentActivity is FragmentActivity){
                    ForceOfflineDialog.newInstance().show(currentActivity.supportFragmentManager,"ForceOfflineDialog")
                }
            }
        })
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }
}