package ru.dbotthepony.mc.otm.block.decorative

import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.ChatFormatting
import net.minecraft.core.BlockPos
import net.minecraft.network.chat.Component
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.monster.Zombie
import net.minecraft.world.item.DyeColor
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.TooltipFlag
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.block.TrapDoorBlock
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.properties.BlockSetType
import ru.dbotthepony.mc.otm.core.TooltipList
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.collect.iteratorOf
import java.util.*
import kotlin.jvm.optionals.getOrNull

class TritaniumTrapdoorBlock(
	val color: DyeColor?,
	properties: Properties = Properties.of()
		.mapColor(color ?: DyeColor.LIGHT_BLUE)
		.explosionResistance(80f)
		.noOcclusion().destroyTime(3f)
		.requiresCorrectToolForDrops()
		.isValidSpawn { _: BlockState, _: BlockGetter, _: BlockPos, _: EntityType<*>? -> false },
	typeSetType: BlockSetType = BlockSetType.IRON
) : TrapDoorBlock(typeSetType, properties) {
	val tooltips = TooltipList()

	private val codec: MapCodec<TritaniumTrapdoorBlock> = RecordCodecBuilder.mapCodec {
		it.group(
			DyeColor.CODEC
				.optionalFieldOf("color")
				.xmap({ it.getOrNull() }, { Optional.ofNullable(it) })
				.forGetter(TritaniumTrapdoorBlock::color),
			propertiesCodec(),
			BlockSetType.CODEC.fieldOf("block_set_type").forGetter(TritaniumTrapdoorBlock::getType)
		).apply(it, ::TritaniumTrapdoorBlock)
	}

	override fun codec(): MapCodec<out TritaniumTrapdoorBlock> {
		return codec
	}

	init {
		tooltips.add { TranslatableComponent("$descriptionId.description0").withStyle(ChatFormatting.DARK_GRAY) }
		tooltips.add { TranslatableComponent("$descriptionId.description1").withStyle(ChatFormatting.DARK_GRAY) }
		tooltips.painted(color)
	}

	override fun appendHoverText(
		itemStack: ItemStack,
		context: Item.TooltipContext,
		lines: MutableList<Component>,
		tooltipType: TooltipFlag
	) {
		super.appendHoverText(itemStack, context, lines, tooltipType)
		tooltips.assemble(itemStack, context, lines)
	}

	override fun canEntityDestroy(
		state: BlockState,
		level: BlockGetter,
		pos: BlockPos,
		entity: Entity
	): Boolean {
		return entity !is Zombie && super.canEntityDestroy(state, level, pos, entity)
	}
}
