package app.padelclub.lestorage

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

class StoredCollection<T : Storable>(var store: Store, val filename: String) {

    var items: MutableList<T> = mutableListOf()

    fun addOrUpdate(item: T) {
        val existingIndex = items.indexOfFirst { it.id == item.id }
        if (existingIndex != -1) {
            items[existingIndex] = item
        } else {
            items.add(item)
        }
        writeToJson()
    }

    fun delete(id: String) {
        items.removeAll { it.id == id }
        writeToJson()
    }

    private fun writeToJson() {
        val json = Json.encodeToString(items)
        store.writeJson(filename, json)
    }

}