package com.bassbooster.soundeffects.equalizer.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bassbooster.soundeffects.equalizer.data.repository.MainRepository
import com.bassbooster.soundeffects.equalizer.data.model.MediaInfo
import com.bassbooster.soundeffects.equalizer.data.model.User
import com.bassbooster.soundeffects.equalizer.utils.MediaAppDetails

import com.bassbooster.soundeffects.equalizer.utils.Resource
import io.reactivex.rxjava3.disposables.CompositeDisposable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class MainViewModel(private val mainRepository: MainRepository) : ViewModel() {
    enum class State {
        PLAY,
        PAUSE
    }
    private val users = MutableLiveData<Resource<List<User>>>()
    private val compositeDisposable = CompositeDisposable()

    val updateInformation = MutableLiveData<MediaInfo>()
    val updateState = MutableLiveData<State>(State.PLAY)
    val updateApp = MutableLiveData<List<MediaAppDetails>>()

    private val _mediaAppDetailsList = MutableLiveData<List<MediaAppDetails>>()

    val mediaAppDetailsList: LiveData<List<MediaAppDetails>> = _mediaAppDetailsList

    fun setMediaAppDetailsList(mediaAppDetailsList: List<MediaAppDetails>) {
        _mediaAppDetailsList.value = mediaAppDetailsList
    }

    init {
        fetchUsers()
    }

    private fun fetchUsers() {
        users.postValue(Resource.loading(null))
        mainRepository.getUsers().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
           users.postValue(Resource.success(it))
        }
//        compositeDisposable.add(
//            mainRepository.getUsers()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe({ userList ->
//                    users.postValue(Resource.success(userList))
//                }, { throwable ->
//                    users.postValue(Resource.error("Something Went Wrong", null))
//                })
//        )
    }

    override fun onCleared() {
        super.onCleared()
        compositeDisposable.dispose()
    }

    fun getUsers(): LiveData<Resource<List<User>>> {
        return users
    }

    fun updateInfo(title: String, description: String){
        val newValue = MediaInfo(title,description)
        updateInformation.postValue(newValue)
    }

    fun updateState(isPlay: Boolean){
        if (isPlay){
            updateState.postValue(State.PLAY)
        }else{
            updateState.postValue(State.PAUSE)
        }
    }
    fun updateApp(app: List<MediaAppDetails>){
        updateApp.postValue(app)
    }
}
