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.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.DoorBlock
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.properties.BlockSetType
import net.minecraft.world.level.material.PushReaction
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 TritaniumDoorBlock(
	val color: DyeColor?,
	properties: Properties = Properties.of()
		.mapColor(color ?: DyeColor.LIGHT_BLUE)
		.explosionResistance(80f)
		.noOcclusion()
		.destroyTime(3f)
		.pushReaction(PushReaction.DESTROY)
		.requiresCorrectToolForDrops(),
	blockSetType: BlockSetType = BlockSetType.IRON,
) : DoorBlock(blockSetType, properties) {
	val tooltips = TooltipList()

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

	override fun codec(): MapCodec<out TritaniumDoorBlock> {
		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(
		p_49816_: ItemStack,
		p_339606_: Item.TooltipContext,
		p_49818_: MutableList<Component>,
		p_49819_: TooltipFlag
	) {
		super.appendHoverText(p_49816_, p_339606_, p_49818_, p_49819_)
		tooltips.assemble(p_49816_, p_339606_, p_49818_)
	}

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