package com.gh.gamecenter.energy.view

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.energy.entity.SignStatusEntity
import com.gh.gamecenter.energy.retrofit.RetrofitManager
import com.gh.gamecenter.energy.utils.EnergyTaskHelper
import com.google.gson.JsonObject
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class EnergyUserViewModel(application: Application, var userId: String) : AndroidViewModel(application) {

    var energy = MutableLiveData<Long>()
    var sign = MutableLiveData<SignStatusEntity>()
    var signStatus = MutableLiveData<SignStatusEntity>()


    @SuppressLint("CheckResult")
    fun getUserEnergy() {
        RetrofitManager.getInstance()
            .api.getUserEnergies(userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<JsonObject>() {
                override fun onSuccess(data: JsonObject) {
                    energy.postValue(data["energy"].asLong)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun signIn() {
        RetrofitManager.getInstance()
            .api.signIn(userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<SignStatusEntity>() {
                override fun onSuccess(data: SignStatusEntity) {
                    EnergyTaskHelper.postEnergyTask("sign_in_cumulatively")
                    EnergyTaskHelper.postEnergyTask("sign_in_continuously")
                    sign.postValue(data)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getSignInfo() {
        RetrofitManager.getInstance()
            .api.getSignStatus(userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<SignStatusEntity>() {
                override fun onSuccess(data: SignStatusEntity) {
                    signStatus.postValue(data)
                }
            })
    }

    class Factory(
        private val mApplication: Application,
        private val mUserId: String
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return EnergyUserViewModel(mApplication, mUserId) as T
        }
    }
}