package com.zyzf.coffeepreorder.database.repository

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingSource
import com.zyzf.coffeepreorder.database.AppContainer
import com.zyzf.coffeepreorder.database.dao.CoffeeDao
import com.zyzf.coffeepreorder.database.model.Coffee
import kotlinx.coroutines.flow.Flow

class OfflineCoffeeRepository(private val coffeeDao: CoffeeDao) : CoffeeRepository {
    override fun getAllCoffees(): Flow<PagingData<Coffee>> = Pager(
        config = PagingConfig(
            pageSize = AppContainer.LIMIT,
            enablePlaceholders = false
        ),
        pagingSourceFactory = coffeeDao::getAllCoffees
    ).flow

    fun getAllCoffeesPagingSource(): PagingSource<Int, Coffee> = coffeeDao.getAllCoffees()
    suspend fun clearCoffees() = coffeeDao.deleteAll()
    override suspend fun getByUid(uid: Int): Coffee? = coffeeDao.getByUid(uid)
    override suspend fun insert(coffee: Coffee): Long = coffeeDao.insert(coffee)
    suspend fun insertCoffees(coffees: List<Coffee>) =
        coffeeDao.insert(*coffees.toTypedArray())
    override suspend fun update(coffee: Coffee): Int = coffeeDao.update(coffee)
    override suspend fun delete(coffee: Coffee) = coffeeDao.delete(coffee)
}