package ru.dbotthepony.kstarbound.defs.world

import com.google.common.collect.ImmutableMap
import com.google.common.collect.ImmutableSet
import ru.dbotthepony.kstarbound.Globals
import ru.dbotthepony.kstarbound.Registries
import ru.dbotthepony.kstarbound.Registry
import ru.dbotthepony.kstarbound.defs.AssetReference
import ru.dbotthepony.kstarbound.defs.ThingDescription
import ru.dbotthepony.kstarbound.defs.tile.TileDamageConfig
import ru.dbotthepony.kstarbound.json.builder.JsonFactory
import ru.dbotthepony.kstarbound.json.builder.JsonFlat

@JsonFactory
data class GrassVariant(
	val name: String,
	val directory: String,
	val images: ImmutableSet<String> = ImmutableSet.of(),
	val hueShift: Double,
	val descriptions: ImmutableMap<String, String> = ImmutableMap.of(),
	val ceiling: Boolean,
	val ephemeral: Boolean,
	val tileDamageParameters: TileDamageConfig,
) {
	@JsonFactory
	data class Data(
		val name: String,
		@JsonFlat
		val descriptions: ThingDescription,
		val images: ImmutableSet<String>,
		val ceiling: Boolean = false,
		val ephemeral: Boolean = true,
		val description: String = name,
		val damageTable: AssetReference<TileDamageConfig>? = null,
		val health: Double = 1.0
	) {
		init {
			require(damageTable == null || damageTable.value != null) { "damageTable must be either absent or point at existing json" }
		}
	}

	companion object {
		fun create(name: String, hueShift: Double): GrassVariant {
			return create(Registries.grassVariants.getOrThrow(name), hueShift)
		}

		fun create(data: Registry.Entry<Data>, hueShift: Double): GrassVariant {
			return GrassVariant(
				name = data.value.name,
				directory = data.file?.computeDirectory() ?: "/",
				images = data.value.images,
				ceiling = data.value.ceiling,
				ephemeral = data.value.ephemeral,
				hueShift = hueShift,
				descriptions = data.value.descriptions.fixDescription(data.value.name).toMap(),
				tileDamageParameters = (data.value.damageTable?.value ?: Globals.grassDamage).copy(totalHealth = data.value.health)
			)
		}
	}
}
