package com.wall.photography.wallpaper.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.wall.photography.wallpaper.MyApp
import com.wall.photography.wallpaper.data.Bean
import com.wall.photography.wallpaper.room.MyDataBase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MyLoveSource( var diff:Int = 0) : PagingSource<Int, Bean>() {
    override fun getRefreshKey(state: PagingState<Int, Bean>): Int? {

        return null
    }



    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Bean> {

        val page = params.key ?: 1
        var pageSize = params.loadSize
        if(page == 1){
            pageSize = MyApp.pageSize
        }
        val indexStart = pageSize * (page - 1)+diff

//        val rspRepository = MyApp.data_Wallpaper?.subList(indexStart, indexStart + pageSize)
        return withContext(Dispatchers.IO) {
            val rspRepository =
                MyDataBase.getInstance().getBeanDao().getPagingLoveWallpaper(true,pageSize, indexStart)
            val items = rspRepository
            val preKey = if (page > 1) page - 1 else null
            val nextKey = if (items.isNotEmpty()) page + 1 else null
            Log.d(
                MyApp.TAG,
                "-----------------Love--indexStart=${indexStart} pageSize=${pageSize} page=${page}    items.size=${items.size}"
            )
            withContext(Dispatchers.Main) {
                Log.d(
                    MyApp.TAG,
                    "--------------Love-----return thread=${Thread.currentThread().name}"
                )
                LoadResult.Page(items, preKey, nextKey)
            }
        }

    }
}


