package com.hanwha.morakmorak.ui.main.home.detail.info

import androidx.lifecycle.MutableLiveData
import com.hanwha.morakmorak.core.BaseViewModel
import com.hanwha.morakmorak.data.local.preferences.UserPreferences
import com.hanwha.morakmorak.data.remote.api.HomeAPI
import com.hanwha.morakmorak.data.remote.model.HomeDetail
import com.hanwha.morakmorak.extensions.with
import com.hanwha.morakmorak.ui.main.home.detail.DetailStatus
import com.hanwha.morakmorak.util.NotNullMutableLiveData
import timber.log.Timber

class DetailInfoViewModel(private val api: HomeAPI, private val prefs: UserPreferences) : BaseViewModel() {

    private val _detailData: MutableLiveData<HomeDetail> = MutableLiveData()
    val detailData: MutableLiveData<HomeDetail>
        get() = _detailData

    private val _joinStatus: NotNullMutableLiveData<DetailStatus> = NotNullMutableLiveData(DetailStatus.NONE)
    val joinStatus: NotNullMutableLiveData<DetailStatus>
        get() = _joinStatus

    fun requestPartiesDetail(partyId: Int) {
        addToDisposable(api.partiesDetail(partyId).with()
                .doOnSubscribe { isProgressVisible.value = true }
                .doOnSuccess { isProgressVisible.value = false}
                .doOnError { isProgressVisible.value = false}
                .subscribe({
                    Timber.i("onResponse!!!")
                    _detailData.value = it
                    for (p in it.participant) {
                        if (p.userId == prefs.userId) {
                            _joinStatus.value = DetailStatus.JOIN
                            return@subscribe
                        }
                    }
                    _joinStatus.value = DetailStatus.NONE
                }, {
                    // handle errors
                    Timber.i("onError!!!")
                    Timber.i(it)
                }))
    }
}
