package dev.fyloz.trial.colorrecipesexplorer.service

import dev.fyloz.trial.colorrecipesexplorer.model.Material
import dev.fyloz.trial.colorrecipesexplorer.model.Mix
import dev.fyloz.trial.colorrecipesexplorer.model.MixMaterial
import dev.fyloz.trial.colorrecipesexplorer.model.mixMaterial
import dev.fyloz.trial.colorrecipesexplorer.repository.MixMaterialRepository
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Service

interface MixMaterialService : ModelService<MixMaterial, MixMaterialRepository> {
    /** Checks if one or more mix materials have the given [material]. */
    fun existsByMaterial(material: Material): Boolean

    /** Creates [MixMaterial]s from the given [map]. The [map] must have the format <Material ID, Quantity>. */
    fun createFromMap(mix: Mix, map: Map<Long, Float>): Collection<MixMaterial>

    /** Creates a [MixMaterial] from the given [pair]. The [pair] must have the format <Material ID, Quantity>. */
    fun createFromPair(mix: Mix, pair: Pair<Long, Float>): MixMaterial
}

@Service
class MixMaterialServiceImpl(
    mixMaterialRepository: MixMaterialRepository,
    @Lazy val materialService: MaterialService
) : AbstractModelService<MixMaterial, MixMaterialRepository>(mixMaterialRepository), MixMaterialService {
    override fun existsByMaterial(material: Material): Boolean = repository.existsByMaterial(material)
    override fun createFromMap(mix: Mix, map: Map<Long, Float>): Collection<MixMaterial> =
        map.map { createFromPair(mix, it.toPair()) }

    override fun createFromPair(mix: Mix, pair: Pair<Long, Float>): MixMaterial {
        val material = materialService.getById(pair.first)
        return mixMaterial(mix = mix, material = material, quantity = pair.second)
    }
}
