package com.gh.gamecenter.personal

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Build
import android.text.TextUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.common.util.DirectUtils
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.MainActivity
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.entity.AddonLinkEntity
import com.gh.gamecenter.entity.AppEntity
import com.gh.gamecenter.entity.HaloAddonEntity
import com.gh.gamecenter.entity.SignEntity
import com.gh.gamecenter.eventbus.EBSkip
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.newsdetail.NewsDetailActivity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.subject.SubjectActivity
import com.gh.gamecenter.wrapper.MainWrapperFragment
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException
import java.text.SimpleDateFormat
import java.util.*

class HaloPersonalViewModel(application: Application) : AndroidViewModel(application) {

    private var mIsRequestingAddons = false

    val appEntity = MutableLiveData<AppEntity>()
    val haloAddData = MutableLiveData<ArrayList<HaloAddonEntity>>()
    val recommendData = MutableLiveData<ArrayList<AddonLinkEntity>>()
    val activityData = MutableLiveData<ArrayList<AddonLinkEntity>>()
    val moreFeaturesData = MutableLiveData<ArrayList<AddonLinkEntity>>()

    @SuppressLint("CheckResult")
    fun getHaloAddons(forcedRefresh: Boolean) {
        if (mIsRequestingAddons && !forcedRefresh) return

        mIsRequestingAddons = true

        RetrofitManager.getInstance()
            .api.newHaloAddons
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ArrayList<HaloAddonEntity>>() {
                override fun onSuccess(data: ArrayList<HaloAddonEntity>) {
                    mIsRequestingAddons = false

                    haloAddData.postValue(data)
                    if (data.isNotEmpty()) {
                        checkUpdate()
                    }
                    data.forEach {
                        when (it.groupType) {
                            "recommend" -> {
                                if (it.addons.size >= 2) {
                                    recommendData.postValue(it.addons)
                                }
                            }

                            "activity" -> activityData.postValue(it.addons)
                            "more_features" -> moreFeaturesData.postValue(it.addons)
                        }
                    }
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)

                    mIsRequestingAddons = false
                }
            })
    }

    fun checkUpdate() {
        RetrofitManager.getInstance()
            .api
            .getUpdate(
                PackageUtils.getGhVersionName(),
                PackageUtils.getGhVersionCode(),
                HaloApp.getInstance().channel,
                Build.VERSION.SDK_INT
            )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<AppEntity>() {
                override fun onResponse(response: AppEntity?) {
                    super.onResponse(response)
                    if (response != null) {
                        appEntity.postValue(response)
                    }
                }
            })
    }

    fun sign(successCallback: (signEntity: SignEntity) -> Unit) {
        val context = getApplication<Application>().applicationContext
        RetrofitManager.getInstance().api
            .postSign(UserManager.getInstance().userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<SignEntity>() {
                override fun onResponse(signEntity: SignEntity?) {
                    if (signEntity != null) {
                        successCallback.invoke(signEntity)
                    }
                }

                override fun onFailure(e: HttpException?) {
                    if (e == null || e.code() != 401) {
                        ToastUtils.toast(context.getString(com.gh.gamecenter.common.R.string.loading_network_error))
                    }
                }
            })
    }

    @SuppressLint("CheckResult")
    fun applyOrReceiveBadge(
        id: String,
        successCallback: (data: ResponseBody) -> Unit,
        failureCallback: () -> Unit
    ) {
        RetrofitManager.getInstance().api
            .applyOrReceiveBadge(id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    successCallback.invoke(data)
                }

                override fun onFailure(exception: java.lang.Exception) {
                    super.onFailure(exception)
                    failureCallback.invoke()
                }
            })
    }

    fun signSkip(context: Context, signEntity: SignEntity) {
        val data = signEntity.data
        val entrance = "(我的光环)+(签到)"
        if (data == null || TextUtils.isEmpty(data.type)) {
            DirectUtils.directToHomeDefaultTab(context)
            return
        }
        when (data.type) {
            "game" -> {
                GameDetailActivity.startGameDetailActivity(context, data.link, entrance)
            }

            "news" -> {
                context.startActivity(NewsDetailActivity.getIntentById(context, data.link, entrance))
            }

            "column" -> {
                SubjectActivity.startSubjectActivity(
                    context,
                    data.link,
                    null,
                    false,
                    null,
                    entrance
                )
            }

            else -> {
                val linkEntity = LinkEntity()
                linkEntity.type = data.type
                linkEntity.link = data.link
                linkEntity.text = data.text
                linkEntity.community = data.community
                linkEntity.display = data.display
                DirectUtils.directToLinkPage(context, linkEntity, entrance, "")
            }
        }
    }

    fun isCanSign(time: Long): Boolean {
        val context = getApplication<Application>().applicationContext
        val formatDay = SimpleDateFormat("dd", Locale.CHINA)
        val lastSignTime = time * 1000
        val curTime = Utils.getTime(context) * 1000
        val lastSignDay = formatDay.format(lastSignTime).toInt()
        val curDay = formatDay.format(curTime).toInt()
        return lastSignDay != curDay || curTime - lastSignTime > 24 * 60 * 60 * 1000
    }

    fun getLoginEntranceByType(loginTag: String): String {
        var entrance = ""
        when (loginTag) {
            "qq" -> entrance = "我的光环-QQ"
            "wechat" -> entrance = "我的光环-微信"
            "weibo" -> entrance = "我的光环-新浪微博"
        }
        return entrance
    }
}