package ru.dbotthepony.mc.otm.entity

import net.minecraft.core.BlockPos
import net.minecraft.core.registries.Registries
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.NbtUtils
import net.minecraft.network.syncher.SynchedEntityData
import net.minecraft.world.entity.Entity
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.state.BlockState
import ru.dbotthepony.mc.otm.registry.game.MEntityTypes

class RideableDummy(level: Level) : Entity(MEntityTypes.RIDEABLE_DUMMY, level) {
	var blockPos: BlockPos = BlockPos.ZERO
	var blockState: BlockState = Blocks.AIR.defaultBlockState()

	constructor(level: Level, blockPos: BlockPos, blockState: BlockState) : this(level) {
		this.blockPos = blockPos
		this.blockState = blockState
	}

	init {
		isNoGravity = true
	    noPhysics = true
	}

	override fun tick() {
		super.tick()

		if (level().isClientSide) return
		if (level().getBlockState(blockPos) != blockState || passengers.isEmpty()) {
			discard()
		}
	}

	override fun defineSynchedData(tag: SynchedEntityData.Builder) {
		// none
	}

	override fun readAdditionalSaveData(tag: CompoundTag) {
		blockPos = NbtUtils.readBlockPos(tag, "block_pos").orElse(BlockPos.ZERO)
		blockState = NbtUtils.readBlockState(this.level().holderLookup(Registries.BLOCK), tag.getCompound("block_state"))
	}

	override fun addAdditionalSaveData(tag: CompoundTag) {
		tag.put("block_pos", NbtUtils.writeBlockPos(blockPos))
		tag.put("block_state", NbtUtils.writeBlockState(blockState))
	}
}
