package ru.fincode.tsudesk.feature.news.data.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import ru.fincode.tsudesk.core.network.model.NetworkResult
import ru.fincode.tsudesk.feature.news.data.datasource.NewsArchiveDataSource
import ru.fincode.tsudesk.feature.news.domain.model.NewsItem

class NewsArchivePagingSource(
    private val dataSource: NewsArchiveDataSource
) : PagingSource<Int, NewsItem>() {

    override fun getRefreshKey(state: PagingState<Int, NewsItem>): Int? {
        val anchor = state.anchorPosition ?: return null
        val page = state.closestPageToPosition(anchor)
        return page?.prevKey?.plus(1) ?: page?.nextKey?.minus(1)
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NewsItem> {
        val page = params.key ?: 1

        return when (val res = dataSource.loadPage(page)) {
            is NetworkResult.Success -> {
                val parsed = res.data
                LoadResult.Page(
                    data = parsed.items,
                    prevKey = if (page == 1) null else page - 1,
                    nextKey = if (parsed.hasNextPage) page + 1 else null
                )
            }
            is NetworkResult.Error -> {
                LoadResult.Error(NewsPagingException(res.error))
            }
        }
    }
}