package kr.co.vividnext.sodalive.settings.signout

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 SignOutViewModel(private val repository: UserRepository) : BaseViewModel() {

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

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

    var reason: String = ""
    var password = ""

    fun signOut(onSuccess: () -> Unit) {
        if (!_isLoading.value!!) {
            if (reason.isBlank()) {
                _toastLiveData.postValue("계정을 삭제하려는 이유를 선택해 주세요.")
                return
            }

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

            _isLoading.value = true
            val request = SignOutRequest(reason.trim(), password)

            compositeDisposable.add(
                repository.signOut(request, "Bearer ${SharedPreferenceManager.token}")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            _isLoading.value = false

                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }

                            if (it.success) {
                                SharedPreferenceManager.clear()
                                onSuccess()
                            }
                        },
                        {
                            _isLoading.value = false
                            it.message?.let { message -> Logger.e(message) }
                            _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                        }
                    )
            )
        }
    }
}
