package io.nexilis.service.data.paging

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import io.nexilis.service.data.daos.MessageDao
import io.nexilis.service.data.daos.RemoteKeyDao
import io.nexilis.service.data.entities.Message
import io.nexilis.service.data.entities.RemoteKey

@OptIn(ExperimentalPagingApi::class)
class MessageRemoteMediator (private val pin: String, private val remoteKeyDao: RemoteKeyDao, private val messageDao: MessageDao): RemoteMediator<Int, Message>() {

    private val REMOTE_KEY_ID = "message"
    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, Message>
    ): MediatorResult {
        return try {
            val loadKey = when (loadType) {
                LoadType.REFRESH -> 0
                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
                LoadType.APPEND -> {
                    state.lastItemOrNull()
                        ?: return MediatorResult.Success(endOfPaginationReached = true)

                    val remoteKey = remoteKeyDao.get(REMOTE_KEY_ID)
                    if (remoteKey == null || remoteKey.nextOffset == 0)
                        return MediatorResult.Success(endOfPaginationReached = true)
                    remoteKey.nextOffset
                }
            }
            remoteKeyDao.insert(
                RemoteKey(
                    id = REMOTE_KEY_ID,
                    nextOffset = loadKey + state.config.pageSize,
                )
            )
            MediatorResult.Success(endOfPaginationReached = 1 < state.config.pageSize)
        } catch (e: Exception) {
            MediatorResult.Error(e)
        }
    }

}