package com.aiosman.ravenow.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.ravenow.entity.AccountLikeEntity
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.entity.LikeItemPagingSource
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.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)
            )
        )
    }

    fun ResetModel() {
        isFirstLoad = true
    }
}