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.GetAudioContentMainItem
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager

class AudioContentNewAllViewModel(
    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 _themeListLiveData = MutableLiveData<List<String>>()
    val themeListLiveData: LiveData<List<String>>
        get() = _themeListLiveData

    private var _newContentListLiveData = MutableLiveData<List<GetAudioContentMainItem>>()
    val newContentListLiveData: LiveData<List<GetAudioContentMainItem>>
        get() = _newContentListLiveData

    private var _newContentTotalCountLiveData = MutableLiveData<Int>()
    val newContentTotalCountLiveData: LiveData<Int>
        get() = _newContentTotalCountLiveData

    private var isLast = false
    private var page = 1
    private val size = 10
    private var selectedTheme = ""

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

            compositeDisposable.add(
                repository.getNewContentAllOfTheme(
                    theme = if (selectedTheme == "전체") {
                        ""
                    } else {
                        selectedTheme
                    },
                    page = page,
                    size = size,
                    token = "Bearer ${SharedPreferenceManager.token}"
                )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            if (it.success && it.data != null) {
                                if (it.data.items.isNotEmpty()) {
                                    page += 1
                                    _newContentListLiveData.postValue(it.data.items)
                                    _newContentTotalCountLiveData.postValue(it.data.totalCount)
                                } else {
                                    isLast = true
                                }
                            } else {
                                if (it.message != null) {
                                    _toastLiveData.postValue(it.message)
                                } else {
                                    _toastLiveData.postValue(
                                        "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                    )
                                }
                            }

                            _isLoading.value = false
                        },
                        {
                            _isLoading.value = false
                            it.message?.let { message -> Logger.e(message) }
                            _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                        }
                    )
            )
        }
    }

    fun getThemeList() {
        compositeDisposable.add(
            repository.getNewContentThemeList(token = "Bearer ${SharedPreferenceManager.token}")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        if (it.success && it.data != null) {
                            val themeList = listOf("전체").union(it.data).toList()
                            _themeListLiveData.postValue(themeList)
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                        }

                        _isLoading.value = false
                    },
                    {
                        _isLoading.value = false
                        it.message?.let { message -> Logger.e(message) }
                        _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                    }
                )
        )
    }

    fun selectTheme(theme: String) {
        isLast = false
        page = 1
        selectedTheme = theme
        getNewContentList()
    }
}
