package kr.co.vividnext.sodalive.following

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 FollowingCreatorViewModel(
    private val repository: FollowingCreatorRepository,
    private val userRepository: UserRepository
) : BaseViewModel() {

    private val _creatorListLiveData = MutableLiveData<List<GetCreatorFollowingAllListItem>>()
    val creatorListLiveData: LiveData<List<GetCreatorFollowingAllListItem>>
        get() = _creatorListLiveData

    private val _creatorListTotalCountLiveData = MutableLiveData(0)
    val creatorListTotalCountLiveData: LiveData<Int>
        get() = _creatorListTotalCountLiveData

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

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

    var page = 1
    var isLast = false
    private var pageSize = 10

    fun getFollowedCreatorAllList() {
        if (!isLast && !_isLoading.value!!) {
            _isLoading.value = true

            compositeDisposable.add(
                repository.getFollowedCreatorAllList(
                    page = page,
                    size = pageSize,
                    token = "Bearer ${SharedPreferenceManager.token}"
                )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            _isLoading.value = false
                            pageSize = 10
                            if (it.success && it.data != null) {
                                val data = it.data
                                if (data.items.isEmpty()) {
                                    isLast = true
                                } else {
                                    page += 1
                                    _creatorListTotalCountLiveData.value = data.totalCount
                                    _creatorListLiveData.value = data.items
                                }
                            } 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 follow(creatorId: Long, follow: Boolean = true, notify: Boolean = true) {
        _isLoading.value = true
        compositeDisposable.add(
            userRepository.creatorFollow(
                creatorId = creatorId,
                follow,
                notify,
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        _isLoading.value = false
                        if (it.success && it.data != null) {
                            isLast = false
                            pageSize *= page
                            page = 1
                            getFollowedCreatorAllList()
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                        }
                    },
                    {
                        _isLoading.value = false
                        it.message?.let { message -> Logger.e(message) }
                        _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                    }
                )
        )
    }
}
