package com.aiosman.riderpro.ui.index.tabs.search

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.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 com.aiosman.riderpro.ui.index.tabs.moment.MomentViewModel.accountService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

object DiscoverViewModel:ViewModel() {
    private val momentService: MomentService = MomentServiceImpl()
    private val _discoverMomentsFlow =
        MutableStateFlow<PagingData<MomentEntity>>(PagingData.empty())
    val discoverMomentsFlow = _discoverMomentsFlow.asStateFlow()
    init {
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    MomentPagingSource(
                        MomentRemoteDataSource(momentService),
                        trend = true
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _discoverMomentsFlow.value = it
            }
        }
    }
    fun refreshPager() {
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    MomentPagingSource(
                        MomentRemoteDataSource(momentService),
                        trend = true
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _discoverMomentsFlow.value = it
            }
        }
    }
}