package com.example.myapplication.database.repository

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.myapplication.database.dao.ProductDao
import com.example.myapplication.database.entities.Product
import kotlinx.coroutines.flow.Flow

class OfflineProductRepository(private val productDao: ProductDao) : ProductRepository {
    override fun getAll(): Flow<PagingData<Product>> {
        return Pager(
            config = PagingConfig(
                pageSize = 8,
                prefetchDistance = 2,
                enablePlaceholders = true,
                initialLoadSize = 12,
                maxSize = 24
            ),
            pagingSourceFactory = {
                productDao.getAll()
            }
        ).flow
    }
    override fun getById(id: Int): Flow<Product> = productDao.getById(id)
    override fun getByCategory(category_id: Int): Flow<PagingData<Product>> {
        return Pager(
            config = PagingConfig(
                pageSize = 8,
                prefetchDistance = 2,
                enablePlaceholders = true,
                initialLoadSize = 12,
                maxSize = 24
            ),
            pagingSourceFactory = {
                productDao.getByCategory(category_id)
            }
        ).flow
    }
    override suspend fun insert(product: Product) = productDao.insert(product)
    override suspend fun insertAll(products: List<Product>) = productDao.insertAll(products)

    override suspend fun clearProducts() = productDao.deleteAll()
}