package com.pixelized.biblib.ui.screen.home.filter.source

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.pixelized.biblib.model.book.Language
import com.pixelized.biblib.repository.search.ISearchRepository
import com.pixelized.biblib.utils.extention.page

class LanguageSearchSource(
    private val searchRepository: ISearchRepository,
    private val search: String?,
    private val limit: Int,
) : PagingSource<Int, Language>() {

    override fun getRefreshKey(state: PagingState<Int, Language>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Language> {
        return try {
            val index = params.page
            val page = searchRepository.searchLanguage(
                search = search,
                limit = limit,
                offset = index * limit
            )
            LoadResult.Page(
                data = page,
                prevKey = if (index == 0) null else index - 1,
                nextKey = if (page.count() < limit) null else index + 1,
            )
        } catch (exception: Exception) {
            Log.e(this::class.java.simpleName, exception.message, exception)
            LoadResult.Error(throwable = exception)
        }
    }
}