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

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

class BookSearchSource(
    private val searchRepository: ISearchRepository,
    private val search: String?,
    private val isNew: Boolean?,
    private val authorId: Int?,
    private val seriesId: Int?,
    private val genreId: Int?,
    private val sortBy: Map<SortType, SortValue?>,
    private val languageId: Int?,
    private val limit: Int,
) : PagingSource<Int, Book>() {

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

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Book> {
        return try {
            val index = params.page
            val page = searchRepository.searchBooks(
                search = search,
                isNew = isNew,
                authorId = authorId,
                seriesId = seriesId,
                genreId = genreId,
                languageId = languageId,
                sortBy = sortBy,
                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)
        }
    }
}