package com.github.nullptroma.wallenc.domain.vault.storages.common

import com.fasterxml.jackson.databind.ObjectMapper
import com.github.nullptroma.wallenc.domain.datatypes.StorageSyncJournal
import com.github.nullptroma.wallenc.domain.datatypes.StorageSyncJournalEntry
import java.util.LinkedHashMap

internal object StorageSyncJournalCodec {
    private val journalJavaType = ObjectMapper().typeFactory.constructMapType(
        LinkedHashMap::class.java,
        String::class.java,
        StorageSyncJournalEntry::class.java,
    )

    fun read(mapper: ObjectMapper, bytes: ByteArray): StorageSyncJournal {
        if (bytes.isEmpty()) {
            return emptyMap()
        }
        return runCatching {
            @Suppress("UNCHECKED_CAST")
            mapper.readValue(bytes, journalJavaType) as StorageSyncJournal
        }.getOrElse {
            emptyMap<String, StorageSyncJournalEntry>()
        }
    }

    fun write(mapper: ObjectMapper, journal: StorageSyncJournal): ByteArray =
        mapper.writeValueAsBytes(journal)
}
