package ru.dbotthepony.mc.otm.block.tech

import net.minecraft.core.BlockPos
import net.minecraft.world.InteractionResult
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.DyeColor
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.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityTicker
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.phys.BlockHitResult
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.VoxelShape
import ru.dbotthepony.mc.otm.block.MatteryBlock
import ru.dbotthepony.mc.otm.block.addSimpleDescription
import ru.dbotthepony.mc.otm.block.entity.tech.AndroidStationBlockEntity
import ru.dbotthepony.mc.otm.block.entity.WorkerState
import ru.dbotthepony.mc.otm.capability.matteryPlayer
import ru.dbotthepony.mc.otm.registry.game.MBlockEntities
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class AndroidStationBlock(val color: DyeColor?) : MatteryBlock(DEFAULT_MACHINE_PROPERTIES), EntityBlock {
	init {
		tooltips.painted(color)
		addSimpleDescription()
		tooltips.blockEntityEnergy()
	}

	override fun useWithoutItem(
		blockState: BlockState,
		level: Level,
		blockPos: BlockPos,
		ply: Player,
		blockHitResult: BlockHitResult
	): InteractionResult {
		if (!ply.matteryPlayer.isAndroid)
			return InteractionResult.FAIL

		return super.useWithoutItem(blockState, level, blockPos, ply, blockHitResult)
	}

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

	override fun getShape(
		p_151964_: BlockState,
		p_151965_: BlockGetter,
		p_151966_: BlockPos,
		p_151967_: CollisionContext
	): VoxelShape {
		return SHAPE
	}

	override fun newBlockEntity(pos: BlockPos, state: BlockState): BlockEntity {
		return AndroidStationBlockEntity(pos, state)
	}

	override fun <T : BlockEntity?> getTicker(
		level: Level,
		state: BlockState,
		type: BlockEntityType<T>
	): BlockEntityTicker<T>? {
		if (level.isClientSide || type !== MBlockEntities.ANDROID_STATION)
			return null

		return BlockEntityTicker { _, _, _, t -> if (t is AndroidStationBlockEntity) t.tick() }
	}

	companion object {
		private val SHAPE = BlockShapes.ANDROID_STATION.computeShape()
	}
}
