package com.github.libretube.ui.models.sources

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.github.libretube.api.SubscriptionHelper
import com.github.libretube.api.obj.StreamItem
import com.github.libretube.repo.FeedProgress

class FeedPagingSource(
    private val hideWatched: Boolean,
    private val showUpcoming: Boolean,
    private val onProgressUpdate: (FeedProgress) -> Unit
) : PagingSource<Int, StreamItem>() {

    companion object {
        const val INITIAL_LOAD_SIZE = 60
        const val LOAD_SIZE = 50
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, StreamItem> {
        return try {
            val page = params.key ?: 0

            // Fetch the complete feed once (simulating pagination by slicing the list)
            val allItems = SubscriptionHelper.getFeed(
                forceRefresh = page == 0,
                onProgressUpdate = onProgressUpdate
            )

            // Simulate pagination by slicing
            val startIndex = page * LOAD_SIZE
            val endIndex = minOf(startIndex + LOAD_SIZE, allItems.size)

            val pageItems = if (startIndex < allItems.size) {
                allItems.subList(startIndex, endIndex)
            } else {
                emptyList()
            }

            val nextKey = if (endIndex < allItems.size) page + 1 else null
            val prevKey = if (page > 0) page - 1 else null

            LoadResult.Page(
                data = pageItems,
                prevKey = prevKey,
                nextKey = nextKey
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, StreamItem>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }
}
