package com.aiosman.ravenow.entity

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.aiosman.ravenow.data.UserService
import java.io.IOException

/**
 * 用户信息分页加载器
 */
class AccountPagingSource(
    private val userService: UserService,
    private val nickname: String? = null,
    private val followerId: Int? = null,
    private val followingId: Int? = null
) : PagingSource<Int, AccountProfileEntity>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AccountProfileEntity> {
        return try {
            val currentPage = params.key ?: 1
            val users = userService.getUsers(
                page = currentPage,
                nickname = nickname,
                followerId = followerId,
                followingId = followingId
            )
            LoadResult.Page(
                data = users.list,
                prevKey = if (currentPage == 1) null else currentPage - 1,
                nextKey = if (users.list.isEmpty()) null else users.page + 1
            )
        } catch (exception: IOException) {
            return LoadResult.Error(exception)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, AccountProfileEntity>): Int? {
        return state.anchorPosition
    }

}