package com.example.myapplication.database.room.repository.offline

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingSource
import com.example.myapplication.database.room.dao.rent.RentDao
import com.example.myapplication.database.room.model.item.ItemFromRent
import com.example.myapplication.database.room.model.rent.Rent
import com.example.myapplication.database.room.repository.AppContainer
import com.example.myapplication.database.room.repository.online.RentRepository
import kotlinx.coroutines.flow.Flow

class OfflineRentRepository(private val rentDao: RentDao) : RentRepository {
    override fun getAllRents(userId: Int?): Flow<PagingData<Rent>> = Pager(
        config = PagingConfig(
            pageSize = AppContainer.LIMIT,
            enablePlaceholders = false
        ),
        pagingSourceFactory = { rentDao.getAll(userId) }
    ).flow

    override suspend fun getRent(uid: Int): List<ItemFromRent> = rentDao.getByUid(uid)

    override suspend fun insertRent(rent: Rent): Long = rentDao.insert(rent).first()

    fun getAllRentsPagingSource(userId: Int?): PagingSource<Int, Rent> = rentDao.getAll(userId)

    suspend fun clearRents() = rentDao.deleteAll()

    suspend fun insertRents(rents: List<Rent>) = rentDao.insert(*rents.toTypedArray())

    override suspend fun deleteRent(rent: Rent) {
        rentDao.delete(rent)
    }
}