package ru.dbotthepony.mc.otm.network

import it.unimi.dsi.fastutil.bytes.ByteArrayList
import it.unimi.dsi.fastutil.io.FastByteArrayOutputStream
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.network.codec.StreamCodec
import net.minecraft.network.protocol.common.custom.CustomPacketPayload
import net.neoforged.neoforge.network.handling.IPayloadContext
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.capability.matteryPlayer
import ru.dbotthepony.mc.otm.client.minecraft
import ru.dbotthepony.mc.otm.core.ResourceLocation
import ru.dbotthepony.mc.otm.menu.ExopackInventoryMenu
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import java.io.ByteArrayInputStream

class MenuDataPacket(val containerId: Int, val bytes: ByteArrayList) : CustomPacketPayload {
	fun write(buff: FriendlyByteBuf) {
		buff.writeVarInt(containerId)
		buff.writeByteListUnbounded(bytes)
	}

	fun play(context: IPayloadContext) {
		if (containerId == ExopackInventoryMenu.CONTAINER_ID) {
			context.player().matteryPlayer.exoPackMenu.mSynchronizer.read(context.player().registryAccess(), bytes)
		} else {
			val menu = context.player().containerMenu as? MatteryMenu ?: return

			if (menu.containerId == containerId)
				menu.mSynchronizer.read(context.player().registryAccess(), bytes)
		}
	}

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

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

		val CODEC: StreamCodec<FriendlyByteBuf, MenuDataPacket> =
			StreamCodec.ofMember(MenuDataPacket::write, ::read)

		fun read(buff: FriendlyByteBuf): MenuDataPacket {
			val containerId = buff.readVarInt()
			return MenuDataPacket(containerId, buff.readByteListUnbounded())
		}
	}
}
