package com.aiosman.riderpro.ui.favourite

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.data.MomentService
import com.aiosman.riderpro.entity.MomentEntity
import com.aiosman.riderpro.entity.MomentPagingSource
import com.aiosman.riderpro.entity.MomentRemoteDataSource
import com.aiosman.riderpro.entity.MomentServiceImpl
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

object FavouriteListViewModel:ViewModel() {
    private val momentService: MomentService = MomentServiceImpl()
    private val _favouriteMomentsFlow =
        MutableStateFlow<PagingData<MomentEntity>>(PagingData.empty())
    val favouriteMomentsFlow = _favouriteMomentsFlow.asStateFlow()
    var isLoading by mutableStateOf(false)
    fun refreshPager(force:Boolean = false) {
        viewModelScope.launch {
            if (force) {
                isLoading = true
            }
            isLoading = false
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    MomentPagingSource(
                        MomentRemoteDataSource(momentService),
                        favoriteUserId = AppState.UserId
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _favouriteMomentsFlow.value = it
            }

        }
    }
    fun ResetModel() {
        isLoading = false
    }
}