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.bike.BikeDao
import com.example.myapplication.database.room.model.bike.Bike
import com.example.myapplication.database.room.model.bike.BikeWithItems
import com.example.myapplication.database.room.repository.AppContainer
import com.example.myapplication.database.room.repository.online.BikeRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

class OfflineBikeRepository(private val bikeDao: BikeDao) : BikeRepository {
    override fun getAllBikes(): Flow<PagingData<Bike>> = Pager(
        config = PagingConfig(
            pageSize = AppContainer.LIMIT,
            enablePlaceholders = false
        ),
        pagingSourceFactory = bikeDao::getAll
    ).flow

    override suspend fun getBike(uid: Int): BikeWithItems {
        val item = bikeDao.getByUid(uid)
            .map { map ->
                map.firstNotNullOf {
                    BikeWithItems(
                        bike = it.key,
                        items = it.value
                    )
                }
            }
            .first()
        return item
    }

    override suspend fun insertBike(bike: Bike) = bikeDao.insert(bike)

    override suspend fun updateBike(bike: Bike) = bikeDao.update(bike)

    override suspend fun deleteBike(bike: Bike) = bikeDao.delete(bike)

    fun getAllBikesPagingSource(): PagingSource<Int, Bike> = bikeDao.getAll()

    suspend fun insertBikes(bikes: List<Bike>) =
        bikeDao.insert(*bikes.toTypedArray())

    suspend fun clearBikes() = bikeDao.deleteAll()
}