From b796c927550bfd4e6828cf58ec60f7070d00f7d1 Mon Sep 17 00:00:00 2001 From: Linnea Gräf Date: Thu, 15 Feb 2024 21:07:35 +0100 Subject: Add json export --- src/main/kotlin/moe/nea/ledger/LedgerLogger.kt | 54 +++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 2 deletions(-) (limited to 'src/main/kotlin') diff --git a/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt b/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt index 4692a13..548b09d 100644 --- a/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt +++ b/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt @@ -1,15 +1,22 @@ package moe.nea.ledger +import com.google.gson.Gson +import com.google.gson.JsonArray +import com.google.gson.JsonObject import net.minecraft.client.Minecraft import net.minecraft.util.ChatComponentText +import java.io.File +import java.text.SimpleDateFormat import java.time.Instant +import java.util.* class LedgerLogger { fun printOut(text: String) { Minecraft.getMinecraft().ingameGUI?.chatGUI?.printChatMessage(ChatComponentText(text)) } - fun logEntry(entry: LedgerEntry) { + + fun printToChat(entry: LedgerEntry) { printOut( """ §e================= TRANSACTION START @@ -23,12 +30,55 @@ class LedgerLogger { ) } + val entries = JsonArray() + + fun logEntry(entry: LedgerEntry) { + entries.add(entry.intoJson()) + commit() + } + + fun commit() { + try { + file.writeText(gson.toJson(entries)) + } catch (ex: Exception) { + ex.printStackTrace() + } + } + + val gson = Gson() + + val file: File = run { + val folder = File("money-ledger") + folder.mkdirs() + val date = SimpleDateFormat("yyyy.MM.dd").format(Date()) + + generateSequence(0) { it + 1 } + .map { + if (it == 0) + folder.resolve("$date.json") + else + folder.resolve("$date-$it.json") + } + .filter { !it.exists() } + .first() + } } + data class LedgerEntry( val transactionType: String, val timestamp: Instant, val totalTransactionCoins: Double, val itemId: String? = null, val itemAmount: Int? = null, -) +) { + fun intoJson(): JsonObject { + return JsonObject().apply { + addProperty("transactionType", transactionType) + addProperty("timestamp", timestamp.toEpochMilli().toString()) + addProperty("totalTransactionValue", totalTransactionCoins) + addProperty("itemId", itemId) + addProperty("itemAmount", itemAmount) + } + } +} -- cgit