package ru.dbotthepony.mc.otm.network

import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.network.codec.StreamCodec
import net.minecraft.network.protocol.common.custom.CustomPacketPayload
import net.minecraft.world.item.ItemStack
import net.neoforged.neoforge.network.handling.IPayloadContext
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.client.minecraft
import ru.dbotthepony.mc.otm.core.ResourceLocation
import ru.dbotthepony.mc.otm.core.readItem
import ru.dbotthepony.mc.otm.core.writeItem

class SetCarriedPacket(val item: ItemStack) : CustomPacketPayload {
	fun write(buff: RegistryFriendlyByteBuf) {
		buff.writeItem(item)
	}

	fun play(context: IPayloadContext) {
		minecraft.player?.containerMenu?.carried = item
	}

	override fun type(): CustomPacketPayload.Type<out CustomPacketPayload> {
		return TYPE
	}

	companion object {
		val TYPE = CustomPacketPayload.Type<SetCarriedPacket>(
			ResourceLocation(
				OverdriveThatMatters.MOD_ID,
				"menu_set_carried"
			)
		)

		val CODEC: StreamCodec<RegistryFriendlyByteBuf, SetCarriedPacket> =
			StreamCodec.ofMember(SetCarriedPacket::write, ::read)

		fun read(buff: RegistryFriendlyByteBuf): SetCarriedPacket {
			return SetCarriedPacket(buff.readItem())
		}
	}
}
