package com.prodhack.moscow2025.data.data_providers

import android.content.ContentResolver
import android.provider.MediaStore
import androidx.paging.PagingSource
import androidx.paging.PagingState

class GalleryPagingSource(
	private val contentResolver: ContentResolver
) : PagingSource<Int, Long>() {

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

			val projection = arrayOf(
				MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATE_ADDED
			)

			val sortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC"

			val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
			val cursor = contentResolver.query(
				uri,
				projection,
				null,
				null,
				"$sortOrder LIMIT $pageSize OFFSET ${page * pageSize}"
			)

			val images = mutableListOf<Long>()
			cursor?.use {
				val idColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
				while (it.moveToNext()) {
					images.add(it.getLong(idColumn))
				}
			}

			val nextKey = if (images.size < pageSize) null else page + 1

			LoadResult.Page(
				data = images,
				prevKey = if (page == 0) null else page - 1,
				nextKey = nextKey
			)

		} catch (e: Exception) {
			LoadResult.Error(e)
		}
	}

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