package com.dlc.exam

import android.app.ActivityManager
import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.multidex.MultiDex
import com.dlc.exam.common.Constants
import com.dlc.exam.sp.EnvSp
import com.dlc.exam.ui.SplashActivity
import com.iflytek.cloud.SpeechConstant
import com.iflytek.cloud.SpeechUtility
import com.rc.core.log.RcLog
import com.rc.core.util.CrashHandler
import com.rc.core.util.ScreenAdapter
import com.rc.httpcore.HttpClient
import com.rc.httpcore.config.ConfigCore
import com.rc.httpcore.config.ConfigFactory
import com.rc.httpcore.vo.response.LearnLoginVo

/**
 * info
 *
 * @author ReiChin_
 */
class ExamApp : Application() {

    companion object {
        @JvmField
        var sLearnLoginVo: LearnLoginVo? = null
    }

    override fun onCreate() {
        super.onCreate()

        ScreenAdapter.initAppDensity(this)

        CrashHandler.initCrash(this)

        initBugly()

        // 初始化网络配置参数
        initHttpConfig()

        // 初始化讯飞语音引擎
        initIflytek()

    }

    private fun initHttpConfig() {
        HttpClient.init(this)
        HttpClient.token = Constants.NetExtra.TOKEN
        HttpClient.vName = BuildConfig.VERSION_NAME
        val envConfig = EnvSp.loadEnv(this)
        val configParam = ConfigFactory.buildReleaseConfig
        Constants.MqttConfig.initMqttConfig(configParam, envConfig)
        ConfigCore.initConfig(configParam, envConfig?.baseUrl, envConfig?.fileBrowserBaseUrl)
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (!topActivityIsSplashActivity()) {
                        Toast.makeText(
                            applicationContext,
                            "登录过期，请重新登录",
                            Toast.LENGTH_SHORT
                        ).show()
                        mUiHandler.sendEmptyMessageAtTime(1, 1500)
                    }
                }

            }, IntentFilter("com.rc.core.token_expired"))
    }

    private val mUiHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (1 == msg.what) {
                // Token过期，进入登录页
                val intent = Intent().apply {
                    flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
                    setClass(this@ExamApp, SplashActivity::class.java)
                }
                removeCallbacksAndMessages(null)
                startActivity(intent)
            }
        }
    }

    private fun topActivityIsSplashActivity(): Boolean {
        return try {
            val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val componentName = activityManager.getRunningTasks(1)[0].topActivity
            SplashActivity::class.java.name == componentName?.className
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 初始化讯飞语音引擎
     */
    private fun initIflytek() {
        // 初始化讯飞语音引擎
        val param = StringBuilder().apply {
            append("${SpeechConstant.APPID}=${Constants.Iflytek.APP_ID},")
            // 设置使用v5+
            append("${SpeechConstant.ENGINE_MODE}=${SpeechConstant.MODE_MSC}")
        }.toString()
        val speechUtility = SpeechUtility.createUtility(this, param)
        val engines = speechUtility.queryAvailableEngines()
        RcLog.info("[Iflytek]讯飞语音引擎初始化结束")
        engines.forEachIndexed { index, value ->
            RcLog.info("[Iflytek]engines[$index]=$value")
        }
    }

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

    private fun initBugly() {
        /*
         * 第三个参数为SDK调试模式开关，调试模式的行为特性如下：
         *   1) 输出详细的Bugly SDK的Log；
         *   2) 每一条Crash都会被立即上报；
         *   3) 自定义日志将会在Logcat中输出。
         * 建议在测试阶段建议设置成true，发布时设置为false。
         */
//        CrashReport.initCrashReport(this, Constants.Bugly.APP_ID, true)
//        CrashReport.initCrashReport(this, Constants.Bugly.APP_ID, false)
    }
}