|
1 | 1 | package org.xodium.illyriaplus.managers |
2 | 2 |
|
3 | 3 | import org.xodium.illyriaplus.data.KingdomData |
| 4 | +import org.xodium.illyriaplus.data.KingdomsData |
4 | 5 | import kotlin.uuid.ExperimentalUuidApi |
5 | 6 | import kotlin.uuid.Uuid |
6 | 7 |
|
7 | 8 | /** |
8 | 9 | * Manages kingdom data storage and retrieval. |
9 | | - * Provides in-memory storage for kingdoms with get-or-create semantics. |
| 10 | + * Provides in-memory storage for kingdoms with get-or-create semantics and JSON persistence. |
10 | 11 | */ |
11 | 12 | @OptIn(ExperimentalUuidApi::class) |
12 | 13 | internal object KingdomManager { |
| 14 | + private val configManager = ConfigManager() |
13 | 15 | private val kingdoms = mutableMapOf<Uuid, KingdomData>() |
14 | 16 |
|
| 17 | + init { |
| 18 | + load() |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Loads kingdoms from disk into memory. |
| 23 | + */ |
| 24 | + fun load() { |
| 25 | + val data = configManager.load("kingdoms", KingdomsData()) |
| 26 | + |
| 27 | + kingdoms.clear() |
| 28 | + kingdoms.putAll(data.kingdoms.associateBy { it.id }) |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Saves all kingdoms to disk. |
| 33 | + */ |
| 34 | + fun save() { |
| 35 | + configManager.save("kingdoms", KingdomsData(kingdoms.values.toList())) |
| 36 | + } |
| 37 | + |
15 | 38 | /** |
16 | 39 | * Gets an existing kingdom by ID, or creates a new one if it doesn't exist. |
| 40 | + * Automatically saves to disk when creating a new kingdom. |
17 | 41 | * |
18 | 42 | * @param id The UUID of the kingdom to get or create. |
19 | 43 | * @return The existing or newly created [KingdomData]. |
20 | 44 | */ |
21 | 45 | fun getOrCreate(id: Uuid): KingdomData = |
22 | 46 | kingdoms.getOrPut(id) { |
23 | | - KingdomData(id = id, name = "<gradient:#FFA751:#FFE259>Kingdom</gradient>", members = emptyList()) |
| 47 | + KingdomData( |
| 48 | + id = id, |
| 49 | + name = "<gradient:#FFA751:#FFE259>Kingdom</gradient>", |
| 50 | + members = emptyList(), |
| 51 | + ).also { save() } |
24 | 52 | } |
25 | 53 |
|
26 | 54 | /** |
|
0 commit comments