package com.aiosman.riderpro.ui.follower

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 androidx.paging.map
import com.aiosman.riderpro.data.AccountFollow
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.entity.FollowItemPagingSource
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UserServiceImpl
import com.aiosman.riderpro.data.UserService
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 FollowerNoticeViewModel : ViewModel() {
    private val accountService: AccountService = AccountServiceImpl()
    private val userService: UserService = UserServiceImpl()
    private val _followerItemsFlow =
        MutableStateFlow<PagingData<AccountFollow>>(PagingData.empty())
    val followerItemsFlow = _followerItemsFlow.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 = {
                    FollowItemPagingSource(
                        accountService
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _followerItemsFlow.value = it
            }
        }
    }

    private fun updateIsFollow(id: Int) {
        val currentPagingData = _followerItemsFlow.value
        val updatedPagingData = currentPagingData.map { follow ->
            if (follow.userId == id) {
                follow.copy(isFollowing = true)
            } else {
                follow
            }
        }
        _followerItemsFlow.value = updatedPagingData
    }
    suspend fun followUser(userId: Int) {
        userService.followUser(userId.toString())
        updateIsFollow(userId)
    }

    suspend fun updateNotice() {
        var now = Calendar.getInstance().time
        accountService.updateNotice(
            UpdateNoticeRequestBody(
                lastLookFollowTime = ApiClient.formatTime(now)
            )
        )
    }
    fun ResetModel() {
        isFirstLoad = true
    }
}