package com.isidroid.spot.data.source.remote.source

import com.isidroid.spot.data.mapper.transform
import com.isidroid.spot.data.mapper.transformToRichSpot
import com.isidroid.spot.data.source.remote.ApiSpot
import com.isidroid.spot.data.source.remote.request.FindSpotRequest
import com.isidroid.spot.model.RichSpot
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
internal class SpotNetworkSource @Inject constructor(private val apiSpot: ApiSpot) {

    fun locateSpots(lat: Double, lng: Double, distance: Int): List<RichSpot>? {
        return try {
            val response = apiSpot.locate(FindSpotRequest(lat = lat, lng = lng, distance = distance)).execute()
            val body = response.body()
            val spots = body?.map { it.transform() }
            val printProfiles = body?.associateBy({ it.id }, { r -> r.profiles?.mapIndexed { index, profileResponse -> profileResponse.transform(r.id, index) } })

            return spots.transformToRichSpot(printProfiles)
        } catch (t: Throwable) {
            Timber.e(t)
            null
        }
    }

    fun find(code: String?): RichSpot? {
        val response = apiSpot.find(code.orEmpty()).execute()
        val body = response.body() ?: return null
        val spot = body.transform()
        val printProfiles = body.profiles?.mapIndexed { index, profileResponse -> profileResponse.transform(spotId = spot.id, index) }

        return RichSpot(spot, printProfiles.orEmpty())
    }
}

