package com.example.dtf.repositories.online.mediator

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import com.example.dtf.api.ServerService
import com.example.dtf.db.AppDatabase
import com.example.dtf.models.Post
import java.io.IOException

@OptIn(ExperimentalPagingApi::class)
class PostMediator (
    private val database: AppDatabase,
    private val serverService: ServerService,
    private val query: String
) : RemoteMediator<Int, Post>(){

    private val postDao = database.postDao()

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, Post>
    ): MediatorResult {
        return try {
            var loadKey = when (loadType) {
                LoadType.REFRESH -> null
                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
                LoadType.APPEND -> {
                    val lastItem = state.lastItemOrNull()
                        ?: return MediatorResult.Success(endOfPaginationReached = true)

                    lastItem.id
                }
            }

            if (loadKey == null) {
                loadKey = 0
            }
            val response = serverService.getPosts(
                category = query.toInt(),
                offset = loadKey,
                limit = state.config.pageSize
            )


            database.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    postDao.deleteByQuery(query)
                }

                for (comment in response.posts) {
                    postDao.insert(comment)
                }
            }

            MediatorResult.Success(endOfPaginationReached = response.nextKey == null)
        } catch (e: IOException) {
            MediatorResult.Error(e)
        }
    }
}