package de.mydevtime.sponge.plugin.lootchest.util

import com.google.common.reflect.TypeToken
import de.mydevtime.sponge.plugin.lootchest.data.ChestData
import ninja.leaping.configurate.commented.CommentedConfigurationNode
import ninja.leaping.configurate.loader.ConfigurationLoader
import org.slf4j.Logger
import java.util.*

class ReadWrite(val conLoader: ConfigurationLoader<CommentedConfigurationNode>, var logger: Logger)
{
	fun writeChests(chests: HashSet<ChestData>)
	{
		val root = conLoader.createEmptyNode()

		for (chest in chests)
		{
			root.getNode("Chests", chest.name).setValue(TypeToken.of(ChestData::class.java), chest)
		}

		conLoader.save(root)

		logger.info("Data written!")
	}

	fun readChests(): HashSet<ChestData>
	{
		val root = conLoader.load()

		val list = HashSet<ChestData>()

		for (node in root.getNode("Chests").childrenMap.entries)
		{
			list.add(node.value.getValue(TypeToken.of(ChestData::class.java)))
		}

		if (list.isEmpty())
		{
			logger.info("No Data to read!")
			return HashSet()
		}

		logger.info("Data read!")

		return list
	}
}