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

import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.dtf.api.ServerService
import com.example.dtf.db.AppDatabase
import com.example.dtf.models.Category
import com.example.dtf.repositories.ICategoryRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

class RestCategoryRepository @Inject constructor(
    private val appDatabase: AppDatabase,
    private val serverService: ServerService
) : ICategoryRepository {

    @OptIn(ExperimentalPagingApi::class)
    override fun getAll(): Flow<PagingData<Category>> = Pager(
        PagingConfig(
            pageSize = 3,
            enablePlaceholders = false
        ),
        remoteMediator = CategoryMediator(appDatabase, serverService),
        pagingSourceFactory = { appDatabase.categoryDao().getAll() }
    ).flow

    override fun getAllCached(): Flow<List<Category>> {
        return appDatabase.categoryDao().getAllCached()
    }

    override fun getFirst(): Flow<Category?> {
        return appDatabase.categoryDao().getFirst()
    }
}