package com.example.myapplication.api.bike.repository

import android.util.Log
import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.bike.mediator.BikeRemoteMediator
import com.example.myapplication.api.bike.remote.toBike
import com.example.myapplication.api.bike.remote.toBikeRemote
import com.example.myapplication.database.room.repository.AppContainer
import com.example.myapplication.database.AppDatabase
import com.example.myapplication.database.remotekeys.repository.offline.OfflineRemoteKeyRepository
import com.example.myapplication.database.room.model.bike.Bike
import com.example.myapplication.database.room.model.bike.BikeWithItems
import com.example.myapplication.database.room.model.item.ItemFromBike
import com.example.myapplication.database.room.repository.offline.OfflineBikeRepository
import com.example.myapplication.database.room.repository.offline.OfflineItemRepository
import com.example.myapplication.database.room.repository.online.BikeRepository
import kotlinx.coroutines.flow.Flow

class RestBikeRepository(
    private val service: MyServerService,
    private val dbBikeRepository: OfflineBikeRepository,
    private val dbItemRepository: OfflineItemRepository,
    private val dbRemoteKeyRepository: OfflineRemoteKeyRepository,
    private val database: AppDatabase
) : BikeRepository {
    override fun getAllBikes(): Flow<PagingData<Bike>> {
        Log.d(RestBikeRepository::class.simpleName, "Get bikes")

        val pagingSourceFactory = { dbBikeRepository.getAllBikesPagingSource() }

        @OptIn(ExperimentalPagingApi::class)
        return Pager(
            config = PagingConfig(
                pageSize = AppContainer.LIMIT,
                enablePlaceholders = false
            ),
            remoteMediator = BikeRemoteMediator(
                service,
                dbBikeRepository,
                dbItemRepository,
                dbRemoteKeyRepository,
                database,
            ),
            pagingSourceFactory = pagingSourceFactory
        ).flow
    }

    override suspend fun getBike(uid: Int): BikeWithItems {
        val bike = service.getBike(uid).toBike()

        val items = service.getItemsForBike(uid).map { x ->
            ItemFromBike(
                x.id,
                x.dateTime,
                x.weight,
                x.radius,
                x.colorbike,
                x.maxCount - service.getRents().flatMap { rent ->
                    rent.items.filter { item -> item.id == x.id }
                }.sumOf { item -> item.count },
                uid
            )
        }
        return BikeWithItems(bike, items)
    }

    override suspend fun insertBike(bike: Bike) {
        service.createBike(bike.toBikeRemote()).toBike()
    }

    override suspend fun updateBike(bike: Bike) {
        service.updateBike(bike.uid, bike.toBikeRemote()).toBike()
    }

    override suspend fun deleteBike(bike: Bike) {
        val cart = service.getUsers()
        cart.forEach { userRemote ->
            userRemote.items = userRemote.items.filter { x -> x.bikeId != bike.uid }
            userRemote.id?.let { service.updateUserCart(it, userRemote) }
        }
        val rents = service.getRents()
        rents.forEach { rentRemote ->
            rentRemote.items = rentRemote.items.filter { x -> x.bikeId != bike.uid }
            service.updateRent(rentRemote.id, rentRemote)
        }
        service.deleteBike(bike.uid)
        dbBikeRepository.deleteBike(bike)
    }
}