package com.swago.app

import android.annotation.SuppressLint
import android.app.Application
import android.content.Intent
import android.os.Handler
import android.os.Message
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.http.RetrofitManager
import com.swago.baseswago.inter.ApiManager
import com.swago.baseswago.model.DomainConfig
import com.swago.baseswago.util.*
import org.jsoup.Jsoup
import java.lang.Exception

/**
 *@date 2022/2/26 11:33
 *description:
 */
class SplashVm(application: Application) : BaseViewModel(application) {

    private val gson by lazy {
        Gson()
    }

    val jumpToLoginLiveData by lazy {
        MutableLiveData<Boolean>()
    }

    var retry = 0

    private val executorService by lazy {
        ThreadPoolUtils.getInstance().executorService
    }

    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            if (UserInfo.getLoginModel() == null) {
                jumpToLoginLiveData.value = false
            } else {
                loginByAuto()
            }
        }
    }

    fun getApiDomain() {
        requestData2(false) {
            requestData {
                val domainData = ApiManager.configApi.getApiDomain()
                setBaseUrl(domainData.host)
                RetrofitManager.resetUrl()

                val data = ApiManager.configApi.getAppConfig()
                SpUtil.putString("configModel", gson.toJson(data))
                UrlConstant.setAgoraId(data.agoral_app_id)
                UrlConstant.setImId(data.im_app_id)
                UrlConstant.lottieDownloadUrl = data.special_zip_url

                if (UserInfo.getLoginModel() == null) {
                    jumpToLoginLiveData.value = false
                } else {
                    loginByAuto()
                }
            }

            requestError {
                retry++
                if (BuildConfig.DEBUG) {
                    getHostUrl("https://github.com/whyNotBanMagna/MvpProject/blob/master/README.md")
                } else {
                    when (retry) {
                        1 -> {
                            getApiDomain()
                        }
                        2 -> {
                            getHostUrl("https://github.com/whyNotBanMagna/MvpProject/blob/master/README.md")
                        }
                        3 -> {
                            getHostUrl("https://github.com/mark-wby/pro/blob/main/README.md")
                        }
                    }
                }
            }
        }
    }

    private fun getHostUrl(url: String) {
        executorService.execute {
            try {
                val document =
                    Jsoup.connect(url)
                        .timeout(2000).get()
                val list = document.text().split(" ")
                list.forEach {
                    if (it.length == 32) {
                        setBaseUrl(MD5Util.decodeBase64(it))
                        RetrofitManager.resetUrl()
                        mHandler.sendEmptyMessage(0)
                        return@execute
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun setBaseUrl(baseUrl: String) {
        if (BuildConfig.DEBUG) {
//            UrlConstant.BASE_URL =   "http:test-api.swago.cn"
//            UrlConstant.BASE_URL =   "http:huawei.swago.cn"
            UrlConstant.BASE_URL =   "https://pro-api.swago.cn"
        } else {
            UrlConstant.BASE_URL = baseUrl
        }
    }

    fun loginByAuto() {
        requestData {
            val data = ApiManager.loginApi.loginByAuto()
            UserInfo.setLoginInfo(data)
            SpUtil.putString("login_info", Gson().toJson(data))
            SwagoLoading.cancelLoadingDialog()
            ARouter.getInstance().build(ARouteConstant.Home.home)
                .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                .navigation()
        }
    }
}