package com.isidroid.spot.repository

import android.content.SharedPreferences
import com.isidroid.spot.model.PrintProfile
import com.isidroid.spot.model.RichSpot
import com.isidroid.spot.data.source.local.source.PrintProfileLocalSource
import com.isidroid.spot.data.source.local.source.SpotLocalSource

private const val ACTIVE_SPOT = "ACTIVE_SPOT"
private const val ACTIVE_PRINT_PROFILE = "ACTIVE_PRINT_PROFILE"

class ActiveSpotRepositoryImpl(
    private val spotLocalSource: SpotLocalSource,
    private val printProfileLocalSource: PrintProfileLocalSource,
    private val prefs: SharedPreferences
) : ActiveSpotRepository {
    override suspend fun makeDefaultSpot(id: String?) = prefs.edit().putString(ACTIVE_SPOT, id).apply()
    override suspend fun makeDefaultPrintProfile(id: String?) = prefs.edit().putString(ACTIVE_PRINT_PROFILE, id).apply()

    override suspend fun getDefaultSpot(): RichSpot? {
        val id = prefs.getString(ACTIVE_SPOT, null)?.let { listOf(it) } ?: return null

        val spot = spotLocalSource.findSpots(id).firstOrNull() ?: return null
        val profiles = printProfileLocalSource.findProfilesInSpots(id)

        return RichSpot(spot, profiles)
    }
}