package ru.dbotthepony.mc.otm.worldgen.feature

import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.world.level.levelgen.feature.Feature
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration
import ru.dbotthepony.mc.otm.block.entity.blackhole.BlackHoleBlockEntity
import ru.dbotthepony.mc.otm.config.ServerConfig
import ru.dbotthepony.mc.otm.core.math.Decimal
import ru.dbotthepony.mc.otm.core.math.nextDecimal
import ru.dbotthepony.mc.otm.data.codec.DecimalCodec
import ru.dbotthepony.mc.otm.registry.game.MBlocks

object BlackHolePlacerFeature : Feature<BlackHolePlacerFeature.Config>(
	RecordCodecBuilder.create {
		it.group(
			DecimalCodec.fieldOf("matter_min").forGetter(Config::minMatter),
			DecimalCodec.fieldOf("matter_max").forGetter(Config::maxMatter)
		).apply(it, ::Config)
	}
) {
	data class Config(val minMatter: Decimal, val maxMatter: Decimal) : FeatureConfiguration

	override fun place(context: FeaturePlaceContext<Config>): Boolean {
		val random = context.random()
		val level = context.level()
		val pos = context.origin()

		val config = context.config()

		if (level.getBlockState(pos).isAir) {
			if (level.setBlock(pos, MBlocks.BLACK_HOLE.defaultBlockState(), 2)) {
				val entity = level.getBlockEntity(pos)

				if (entity is BlackHoleBlockEntity) {
					entity.mass = random.nextDecimal(config.minMatter, config.maxMatter) * ServerConfig.Blackhole.BASELINE_MASS
				}

				return true
			}
		}

		return false
	}
}
