package com.develop.auth.ui

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.ToastUtils
import com.develop.auth.R
import com.develop.food.base.api.FoodRepository
import com.develop.food.base.common.API_TOKEN
import com.develop.food.base.common.CURRENT_USER_ID_TAG
import com.develop.food.base.common.LOGIN_TAG
import com.develop.food.base.common.RECORD_ACCOUNT
import com.develop.food.base.common.RECORD_PASSWORD
import com.develop.food.base.http.observeStatus
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.UserInfo
import com.develop.food.base.utils.MmkvUtils

class MemberViewModel(application: Application) : AndroidViewModel(application) {
    private var verifyCodeKey: String? = null
    val chooseAvatar = MutableLiveData<Int>()
    var enterFromHome: Boolean = false
    var loginRecord: Boolean = false

    fun register(email: String, password: String): LiveData<Boolean> {
        val dispatchLiveData = MutableLiveData<Boolean>()
        FoodRepository.register(email, password).observeStatus(
            onSuccess = {
                login(email, password).observeForever {
                    dispatchLiveData.value = it
                }
            },
            onFailed = {
                it?.desc?.let { msg ->
                    if (msg == "账号已存在") {
                        ToastUtils.showShort("The email has been already registered.")
                    } else {
                        ToastUtils.showShort(msg)
                    }
                }
                dispatchLiveData.value = false
            }
        )
        return dispatchLiveData
    }

    fun login(email: String, password: String): LiveData<Boolean> {
        val dispatchLiveData = MutableLiveData<Boolean>()
        FoodRepository.login(email, password).observeStatus(
            onSuccess = {
                MmkvUtils.save(API_TOKEN, it?.token)
                MmkvUtils.save(LOGIN_TAG, true)
                MmkvUtils.save(CURRENT_USER_ID_TAG, it?.user?.id?.toLong() ?: 100001)
                val userInfo = UserInfo(
                    it?.user?.id?.toLong() ?: 0L,
                    it?.user?.nickname?.toString(),
                    it?.user?.portrait,
                    it?.user?.gender,
                    it?.user?.age ?: 0
                )
                if (loginRecord) {
                    MmkvUtils.save(RECORD_ACCOUNT, email)
                    MmkvUtils.save(RECORD_PASSWORD, password)
                } else {
                    MmkvUtils.save(RECORD_ACCOUNT, null as? String?)
                    MmkvUtils.save(RECORD_PASSWORD, null as? String?)
                }
                FoodDataProvider.getUserDatabase().userInfoDao().updateUserInfo(userInfo)
                dispatchLiveData.value = true
            },
            onFailed = {
                if (it?.code == -1) {
                    ToastUtils.showShort(it.desc)
                } else {
                    it?.desc?.let { msg ->
                        ToastUtils.showShort(getApplication<Application>().getString(R.string.account_password_error))
                    }
                }
                dispatchLiveData.value = false
            }
        )
        return dispatchLiveData
    }

    fun sendEmail(email: String): LiveData<Boolean> {
        val liveData = MutableLiveData<Boolean>()
        FoodRepository.sendVerifyCode(email).observeStatus(
            onSuccess = {
                verifyCodeKey = it?.verifyCodeKey
                liveData.value = true
            },
            onFailed = {
                it?.desc?.let { msg ->
                    ToastUtils.showShort(getApplication<Application>().getString(R.string.account_not_exist))
                }
                liveData.value = false
            }
        )
        return liveData
    }

    fun resetPassword(
        email: String,
        captcha: String,
        password: String
    ): LiveData<Boolean> {
        val liveData = MutableLiveData<Boolean>()
        FoodRepository.updatePassword(
            email, password, verifyCodeKey ?: "", captcha
        ).observeStatus(
            onSuccess = {
                liveData.value = true
            },
            onFailed = {
                it?.desc?.let { msg ->
                    if ("验证码不正确" == msg) {
                        ToastUtils.showShort(getApplication<Application>().getString(R.string.captcha_incorrect))
                    } else {
                        ToastUtils.showShort(msg)
                    }
                }
                liveData.value = false
            }
        )
        return liveData
    }


    fun cancelAccount(): LiveData<Any> {
        val liveData = MutableLiveData<Any>()
        FoodRepository.cancelAccount().observeStatus(onSuccess = {
            liveData.value = true
        }, onFailed = {
            liveData.value = false
        })
        return liveData
    }
}