package kr.co.vividnext.sodalive.audio_content.all

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.audio_content.AudioContentRepository
import kr.co.vividnext.sodalive.audio_content.main.GetAudioContentRankingItem
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager

class AudioContentRankingAllViewModel(
    private val repository: AudioContentRepository
) : BaseViewModel() {
    private val _toastLiveData = MutableLiveData<String?>()
    val toastLiveData: LiveData<String?>
        get() = _toastLiveData

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

    private var _dateStringLiveData = MutableLiveData<String>()
    val dateStringLiveData: LiveData<String>
        get() = _dateStringLiveData

    private var _contentRankingSortListLiveData = MutableLiveData<List<String>>()
    val contentRankingSortListLiveData: LiveData<List<String>>
        get() = _contentRankingSortListLiveData

    private var _contentRankingItemsLiveData = MutableLiveData<List<GetAudioContentRankingItem>>()
    val contentRankingItemsLiveData: LiveData<List<GetAudioContentRankingItem>>
        get() = _contentRankingItemsLiveData

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

    private var selectedSort = "매출"

    fun getAudioContentRanking() {
        if (!_isLoading.value!! && !isLast && page <= 5) {
            _isLoading.value = true
            compositeDisposable.add(
                repository.getContentRanking(
                    page = page,
                    size = pageSize,
                    sortType = selectedSort,
                    token = "Bearer ${SharedPreferenceManager.token}"
                )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            if (it.success && it.data != null) {
                                _isLoading.value = false
                                _dateStringLiveData.value =
                                    "${it.data.startDate}~${it.data.endDate}"

                                if (it.data.items.isNotEmpty()) {
                                    page += 1
                                    _contentRankingItemsLiveData.value = it.data.items
                                } else {
                                    isLast = true
                                }
                            } else {
                                _isLoading.value = false
                                if (it.message != null) {
                                    _toastLiveData.postValue(it.message)
                                } else {
                                    _toastLiveData.postValue(
                                        "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                    )
                                }
                            }
                        },
                        {
                            it.message?.let { message -> Logger.e(message) }
                            _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                        }
                    )
            )
        }
    }

    fun getAudioContentRankingSortType() {
        compositeDisposable.add(
            repository.getContentRankingSortType(token = "Bearer ${SharedPreferenceManager.token}")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        if (it.success && it.data != null) {
                            _contentRankingSortListLiveData.value = it.data!!
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                        }
                    },
                    {
                        it.message?.let { message -> Logger.e(message) }
                        _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                    }
                )
        )
    }

    fun selectSort(sort: String) {
        page = 1
        isLast = false
        selectedSort = sort
        getAudioContentRanking()
    }
}
