package com.live.mylivewallpaper.paging;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.paging.PagingSource;
import androidx.paging.PagingState;

import com.live.mylivewallpaper.data.ResultData;
import com.live.mylivewallpaper.help.Common;
import com.live.mylivewallpaper.help.Db;

import java.util.List;

import kotlin.coroutines.Continuation;

public class MyPagingSource extends PagingSource<Integer, ResultData> {
     public static int pageSize = 10;
    private int wallpaperType;

    public MyPagingSource(int wallpaperType) {
        this.wallpaperType = wallpaperType;
    }

    @Nullable
    @Override
    public Integer getRefreshKey(@NonNull PagingState<Integer, ResultData> pagingState) {
        return null;
    }

    @Nullable
    @Override
    public Object load(@NonNull LoadParams<Integer> loadParams, @NonNull Continuation<? super LoadResult<Integer, ResultData>> continuation) {

        try {
            int page = loadParams.getKey() != null ? loadParams.getKey() : 1;

            List<ResultData> data = Db.queryData(wallpaperType,page);
//            Common.logMsg("-----load---------"+wallpaperType+"----page="+page+"'--data="+data.size());
            return new LoadResult.Page<>(
                    data,
                    page > 1 ? page - 1 : null,
                    data.isEmpty() ? null : page + 1
            );
        } catch (Exception e) {
            return new LoadResult.Error<>(e);
        }
    }
}

