package com.aiosman.riderpro.ui.like

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.AccountLikeEntity
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.entity.LikeItemPagingSource
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


object LikeNoticeViewModel : ViewModel() {
    private val accountService: AccountService = AccountServiceImpl()
    private val _likeItemsFlow = MutableStateFlow<PagingData<AccountLikeEntity>>(PagingData.empty())
    val likeItemsFlow = _likeItemsFlow.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 = {
                    LikeItemPagingSource(
                        accountService
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _likeItemsFlow.value = it
            }
        }
    }

    suspend fun updateNotice() {
        var now = Calendar.getInstance().time
        accountService.updateNotice(
            UpdateNoticeRequestBody(
                lastLookLikeTime = ApiClient.formatTime(now)
            )
        )
    }
}