package asm.mixins;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import java.util.List;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.network.handler.DecoderHandler;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.PacketType;
import net.minecraft.network.packet.s2c.play.BundleDelimiterS2CPacket;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.At.Shift;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;

@Environment(EnvType.CLIENT)
@Mixin({DecoderHandler.class})
public class MixinDecoderHandler {
   @Inject(
      method = {"decode"},
      at = {@At(
         value = "INVOKE",
         target = "Lio/netty/buffer/ByteBuf;readableBytes()I",
         ordinal = 1,
         shift = Shift.BEFORE,
         remap = false
      )},
      require = 0,
      locals = LocalCapture.CAPTURE_FAILSOFT
   )
   private void crucifixbeta$ignoreViaBundleDelimiterExtraBytes(
      ChannelHandlerContext context, ByteBuf buf, List<Object> out, CallbackInfo ci, int packetSize, Packet<?> packet, PacketType<?> packetType
   ) {
      if (packet instanceof BundleDelimiterS2CPacket && buf.readableBytes() > 0) {
         buf.skipBytes(buf.readableBytes());
      }
   }
}
