package com.github.nullptroma.wallenc.usecases

import com.github.nullptroma.wallenc.domain.interfaces.IStorage
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.buildJsonArray

internal object StorageDomainJsonIo {
    val json: Json = Json {
        prettyPrint = true
        ignoreUnknownKeys = true
        explicitNulls = false
    }

    suspend fun readArray(storage: IStorage, fileName: String): JsonArray {
        return try {
            val text = storage.accessor.openRead(fileName).use { stream ->
                stream.readBytes().decodeToString()
            }
            if (text.isBlank()) {
                JsonArray(emptyList())
            } else {
                when (val parsed = json.parseToJsonElement(text)) {
                    is JsonArray -> parsed
                    else -> JsonArray(emptyList())
                }
            }
        } catch (_: Exception) {
            JsonArray(emptyList())
        }
    }

    suspend fun writeArray(storage: IStorage, fileName: String, data: List<JsonElement>) {
        val payload = buildJsonArray { data.forEach { add(it) } }
        storage.accessor.openWrite(fileName).use { stream ->
            stream.write(json.encodeToString(JsonArray.serializer(), payload).encodeToByteArray())
        }
    }
}
