package com.gh.gamecenter.feedback.view.qa

import android.annotation.SuppressLint
import android.app.Application
import android.os.Build
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.exposure.meta.MetaUtil
import com.gh.gamecenter.common.exposure.meta.MetaUtil.getBase64EncodedIMEI
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.core.provider.IAppProvider
import com.gh.gamecenter.core.provider.IPackageUtilsProvider
import com.gh.gamecenter.feedback.HaloApp
import com.gh.gamecenter.feedback.R
import com.gh.gamecenter.feedback.retrofit.RetrofitManager
import okhttp3.ResponseBody

class QaFeedbackViewModel(application: Application, private val contentId: String) : AndroidViewModel(application) {

    val feedbackSuccess = MutableLiveData<Boolean>()

    @SuppressLint("CheckResult")
    fun qaSuggestions(message: String) {
        val packageUtilsConfig = TheRouter.get(IPackageUtilsProvider::class.java)
        val appProvider = TheRouter.get(IAppProvider::class.java)
        val map = hashMapOf<String, Any>()
        map["message"] = message
        map["ghversion"] = packageUtilsConfig?.getGhVersionName() ?: ""
        map["channel"] = appProvider?.getChannel() ?: ""
        map["type"] = Build.MODEL
        map["sdk"] = Build.VERSION.SDK_INT.toString()
        map["version"] = Build.VERSION.RELEASE
        map["source"] = HaloApp.getInstance().getString(R.string.app_name)
        map["jnfj"] = getBase64EncodedIMEI()
        map["manufacturer"] = Build.MANUFACTURER
        map["rom"] = MetaUtil.getRom().name + " " + MetaUtil.getRom().versionName

        val requestBody = map.toRequestBody()
        RetrofitManager.getInstance().api
            .qaSuggestions(contentId, requestBody)
            .compose(singleToMain())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    feedbackSuccess.postValue(true)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    feedbackSuccess.postValue(false)
                }
            })
    }

    class Factory(private val contentId: String) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return QaFeedbackViewModel(HaloApp.getInstance(), contentId) as T
        }
    }
}