package com.pixelized.server.lwa.services.item

import com.pixelized.shared.lwa.model.item.ItemJson
import com.pixelized.shared.lwa.model.item.factory.ItemJsonFactory
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 ItemService(
    private val itemStore: ItemStore,
    factory: ItemJsonFactory,
) {
    private val scope = CoroutineScope(Dispatchers.IO + Job())

    private val itemHashFlow = itemStore.itemsFlow()
        .map { items -> items.associate { it.id to factory.convertToJson(it) } }
        .stateIn(
            scope = scope,
            started = SharingStarted.Eagerly,
            initialValue = emptyMap()
        )

    fun items(): List<ItemJson> {
        return itemHashFlow.value.values.toList()
    }

    fun item(itemId: String): ItemJson? {
        return itemHashFlow.value[itemId]
    }

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

    @Throws
    suspend fun delete(itemId: String) {
        itemStore.delete(id = itemId)
    }
}
