package kr.co.vividnext.sodalive.user.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.orhanobut.logger.Logger
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.user.UserRepository

class LoginViewModel(private val repository: UserRepository) : BaseViewModel() {

    var email = ""
    var password = ""

    private val _visiblePasswordLiveData = MutableLiveData(false)
    val visiblePasswordLiveData: LiveData<Boolean>
        get() = _visiblePasswordLiveData

    private val _toastLiveData = MutableLiveData<String?>()
    val toastLiveData: LiveData<String?>
        get() = _toastLiveData

    private var _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean>
        get() = _isLoading

    fun login(onSuccess: (String?) -> Unit) {
        if (email.isBlank()) {
            _toastLiveData.postValue("이메일을 입력하세요.")
            return
        }

        if (password.isBlank()) {
            _toastLiveData.postValue("비밃번호를 입력하세요.")
            return
        }

        _isLoading.value = true
        val request = LoginRequest(email, password)
        compositeDisposable.add(
            repository.login(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        _isLoading.value = false
                        if (it.success && it.data != null) {
                            SharedPreferenceManager.token = it.data.token
                            SharedPreferenceManager.email = it.data.email
                            SharedPreferenceManager.userId = it.data.userId
                            SharedPreferenceManager.nickname = it.data.nickname
                            SharedPreferenceManager.profileImage = it.data.profileImage
                            onSuccess(it.message)
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                        }
                    },
                    {
                        _isLoading.value = false
                        it.message?.let { message -> Logger.e(message) }
                        _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                    }
                )
        )
    }

    fun onClickVisiblePassword() {
        _visiblePasswordLiveData.postValue(!_visiblePasswordLiveData.value!!)
    }
}
