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

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.extensions.with
import com.hanwha.morakmorak.util.NotNullMutableLiveData
import timber.log.Timber

/**
 * Created by aaron on 10/09/2019
 */
class HomeDetailViewModel(private val api: HomeAPI, private val prefs: UserPreferences) : BaseViewModel() {

//    lateinit var onJoinClick: (View, Int) -> Unit

    private val _update: NotNullMutableLiveData<Boolean> = NotNullMutableLiveData(false)
    val update: NotNullMutableLiveData<Boolean>
        get() = _update

    var isJoin = false

    fun onJoinClick(partyId: Int) {
        if (isJoin) {
            cancelParty(partyId)
        } else {
            joinParty(partyId)
        }
    }

    fun joinParty(partyId: Int) {
        val params = mutableMapOf<String, Any>(
                "partyId" to partyId,
                "userId" to prefs.userId
        )

        addToDisposable(api.joinParty(params).with()
                .doOnSubscribe { isProgressVisible.value = true }
                .doOnSuccess { isProgressVisible.value = false}
                .doOnError { isProgressVisible.value = false}
                .subscribe({
                    Timber.i("onResponse!!!")
                    _update.value = true
                }, {
                    // handle errors
                    Timber.i("onError!!!")
                    Timber.i(it)
                }))
    }

    fun cancelParty(partyId: Int) {
        val params = mutableMapOf<String, Any>(
                "partyId" to partyId,
                "userId" to prefs.userId
        )

        addToDisposable(api.cancelJoining(params).with()
                .doOnSubscribe { isProgressVisible.value = true }
                .doOnSuccess { isProgressVisible.value = false}
                .doOnError { isProgressVisible.value = false}
                .subscribe({
                    Timber.i("onResponse!!!")
                    _update.value = true
                }, {
                    // handle errors
                    Timber.i("onError!!!")
                    Timber.i(it)
                }))
    }
}

enum class DetailStatus(val status: Int) {
    NONE(0), JOIN(1), LEADER(2)
}