package kr.co.vividnext.sodalive.message

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.live.LiveRepository
import kr.co.vividnext.sodalive.live.room.detail.GetRoomDetailUser
import kr.co.vividnext.sodalive.user.UserRepository

class SelectMessageRecipientViewModel(
    private val liveRepository: LiveRepository,
    private val userRepository: UserRepository
) : BaseViewModel() {

    private val _searchUserLiveData =
        MutableLiveData<List<GetRoomDetailUser>>()
    val searchUserLiveData: LiveData<List<GetRoomDetailUser>>
        get() = _searchUserLiveData

    fun searchUser(nickname: String) {
        if (nickname.length > 1) {
            compositeDisposable.add(
                userRepository.searchUser(nickname, "Bearer ${SharedPreferenceManager.token}")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            if (it.success && it.data != null) {
                                _searchUserLiveData.postValue(it.data!!)
                            } else {
                                _searchUserLiveData.postValue(emptyList())
                            }
                        },
                        {
                            it.message?.let { message -> Logger.e(message) }
                            _searchUserLiveData.postValue(emptyList())
                        }
                    )
            )
        } else {
            compositeDisposable.add(
                liveRepository.recentVisitRoomUsers("Bearer ${SharedPreferenceManager.token}")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            if (it.success && it.data != null) {
                                _searchUserLiveData.postValue(it.data!!)
                            } else {
                                _searchUserLiveData.postValue(emptyList())
                            }
                        },
                        {
                            it.message?.let { message -> Logger.e(message) }
                            _searchUserLiveData.postValue(emptyList())
                        }
                    )
            )
        }
    }
}
