package com.pixelized.server.lwa.services.alteration

import com.pixelized.shared.lwa.model.alteration.AlterationJson
import com.pixelized.shared.lwa.model.alteration.AlterationJsonFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn

class AlterationService(
    private val alterationStore: AlterationStore,
    factory: AlterationJsonFactory,
) {
    private val scope = CoroutineScope(Dispatchers.IO + Job())

    private val alterationHashFlow = alterationStore.alterationsFlow()
        .map { alterations -> alterations.associate { it.id to factory.convertToJson(it) } }
        .stateIn(
            scope = scope,
            started = SharingStarted.Eagerly,
            initialValue = emptyMap()
        )

    fun alterations(): List<AlterationJson> {
        return alterationHashFlow.value.values.toList()
    }

    fun alteration(alterationId: String): AlterationJson? {
        return alterationHashFlow.value[alterationId]
    }

    @Throws
    suspend fun save(
        json: AlterationJson,
        create: Boolean,
    ) {
        alterationStore.save(
            json = json,
            create = create,
        )
    }

    @Throws
    fun delete(alterationId: String) {
        alterationStore.delete(id = alterationId)
    }
}
