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

import net.minecraft.core.BlockPos
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.item.DyeColor
import net.minecraft.world.item.context.BlockPlaceContext
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.EntityBlock
import net.minecraft.world.level.block.SoundType
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.level.block.state.properties.BooleanProperty
import net.minecraft.world.level.material.MapColor
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.Shapes
import net.minecraft.world.phys.shapes.VoxelShape
import ru.dbotthepony.mc.otm.block.RotatableMatteryBlock
import ru.dbotthepony.mc.otm.block.entity.decorative.CargoCrateBlockEntity
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class CargoCrateBlock(val color: DyeColor?) : RotatableMatteryBlock(
	Properties.of().mapColor(color?.mapColor ?: MapColor.COLOR_BLUE).requiresCorrectToolForDrops().sound(SoundType.METAL).strength(1.5f, 30.0f)
), EntityBlock {
	override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity {
		return CargoCrateBlockEntity(blockPos, blockState)
	}

	override fun createBlockStateDefinition(builder: StateDefinition.Builder<Block, BlockState>) {
		super.createBlockStateDefinition(builder)
		builder.add(IS_OPEN)
	}

	override fun getStateForPlacement(context: BlockPlaceContext): BlockState? {
		return super.getStateForPlacement(context)?.setValue(IS_OPEN, false)
	}

	@Suppress("OVERRIDE_DEPRECATION")
	override fun hasAnalogOutputSignal(p_60457_: BlockState): Boolean {
		return true
	}

	@Suppress("OVERRIDE_DEPRECATION")
	override fun getAnalogOutputSignal(p_60487_: BlockState, level: Level, p_60489_: BlockPos): Int {
		val tile = level.getBlockEntity(p_60489_) as? CargoCrateBlockEntity ?: return 0
		return AbstractContainerMenu.getRedstoneSignalFromContainer(tile.container)
	}

	override fun getShape(
		p_60555_: BlockState,
		p_60556_: BlockGetter,
		p_60557_: BlockPos,
		p_60558_: CollisionContext
	): VoxelShape {
		if (p_60555_[IS_OPEN]) {
			return CARGO_CRATE_OPEN
		} else {
			return Shapes.block()
		}
	}

	companion object {
		@JvmField
		val IS_OPEN: BooleanProperty = BooleanProperty.create("open")
		val CARGO_CRATE_OPEN: VoxelShape = BlockShapes.CARGO_CRATE_OPEN.computeShape()
	}
}
