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.Category
import java.io.IOException

@OptIn(ExperimentalPagingApi::class)
class CategoryMediator (
    private val database: AppDatabase,
    private val serverService: ServerService
) : RemoteMediator<Int, Category>(){

    private val categoryDao = database.categoryDao()

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, Category>
    ): 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.getCategories(
                offset = loadKey,
                limit = state.config.pageSize
            )


            database.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    for (category in response.categories) {
                        categoryDao.delete(category)
                    }
                }

                for (category in response.categories) {
                    categoryDao.insert(category)
                }
            }

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