package com.isidroid.spot.repository

import com.isidroid.spot.SpotListException
import com.isidroid.spot.data.mapper.convertToMap
import com.isidroid.spot.data.mapper.transformToRichSpot
import com.isidroid.spot.model.RichSpot
import com.isidroid.spot.data.source.local.source.PrintProfileLocalSource
import com.isidroid.spot.data.source.local.source.SpotLocalSource
import com.isidroid.spot.data.source.remote.source.SpotNetworkSource

internal class SpotRepositoryImpl(
    private val spotNetworkSource: SpotNetworkSource,
    private val spotLocalSource: SpotLocalSource,
    private val printProfileLocalSource: PrintProfileLocalSource
) : SpotRepository {
    override suspend fun locateSpots(lat: Double, lng: Double, distance: Int): List<RichSpot> {
        return spotNetworkSource.locateSpots(lat = lat, lng = lng, distance = distance) ?: throw SpotListException()
    }

    override suspend fun findRichSpot(code: String?): RichSpot? = spotNetworkSource.find(code)

    override suspend fun findLocalRichSpots(ids: List<String>): List<RichSpot>? {
        val spots = spotLocalSource.findSpots(ids)
        val profiles = printProfileLocalSource.findProfilesInSpots(ids).convertToMap()
        return spots.transformToRichSpot(profiles)
    }

    override suspend fun save(richSpot: RichSpot?) {
        richSpot ?: return

        spotLocalSource.insert(richSpot.spot)
        printProfileLocalSource.insert(*richSpot.printProfiles.toTypedArray())
    }
}