package com.aiosman.riderpro.ui.favourite

import android.icu.util.Calendar
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.entity.AccountFavouriteEntity
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.entity.FavoriteItemPagingSource
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.api.ApiClient
import com.aiosman.riderpro.data.api.UpdateNoticeRequestBody
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * 收藏消息列表的 ViewModel
 */
object FavouriteNoticeViewModel : ViewModel() {
    private val accountService: AccountService = AccountServiceImpl()
    private val _favouriteItemsFlow =
        MutableStateFlow<PagingData<AccountFavouriteEntity>>(PagingData.empty())
    val favouriteItemsFlow = _favouriteItemsFlow.asStateFlow()
    var isFirstLoad = true

    fun reload(force: Boolean = false) {
        if (!isFirstLoad && !force) {
            return
        }
        isFirstLoad = false
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    FavoriteItemPagingSource(
                        accountService
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _favouriteItemsFlow.value = it
            }
        }
    }
    // 更新收藏消息的查看时间
    suspend fun updateNotice() {
        var now = Calendar.getInstance().time
        accountService.updateNotice(
            UpdateNoticeRequestBody(
                lastLookFavouriteTime = ApiClient.formatTime(now)
            )
        )
    }

    fun ResetModel() {
        isFirstLoad = true
    }
}