package fr.bglands.client.fabric;

import fr.bglands.client.protocol.ProtocolConstants;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;

import java.util.Arrays;

/**
 * Raw, unprefixed bytes on the Bukkit plugin messaging channel. Paper sees the
 * exact JSON bytes and does not need Fabric on the server.
 */
public record BgLandsRawPayload(byte[] data) implements CustomPacketPayload {
    public static final Type<BgLandsRawPayload> TYPE = new Type<>(Identifier.parse(ProtocolConstants.CHANNEL));
    public static final StreamCodec<RegistryFriendlyByteBuf, BgLandsRawPayload> CODEC =
            StreamCodec.of(BgLandsRawPayload::write, BgLandsRawPayload::read);

    public BgLandsRawPayload {
        data = Arrays.copyOf(data, data.length);
        if (data.length > ProtocolConstants.MAX_PAYLOAD_BYTES) {
            throw new IllegalArgumentException("BG Lands UI payload is too large");
        }
    }

    @Override
    public byte[] data() {
        return Arrays.copyOf(data, data.length);
    }

    @Override
    public Type<BgLandsRawPayload> type() {
        return TYPE;
    }

    private static BgLandsRawPayload read(RegistryFriendlyByteBuf buffer) {
        int readable = buffer.readableBytes();
        int retained = Math.min(readable, ProtocolConstants.MAX_PAYLOAD_BYTES);
        byte[] data = new byte[retained];
        buffer.readBytes(data);
        if (readable > retained) {
            buffer.skipBytes(readable - retained);
            return new BgLandsRawPayload(new byte[0]);
        }
        return new BgLandsRawPayload(data);
    }

    private static void write(RegistryFriendlyByteBuf buffer, BgLandsRawPayload payload) {
        buffer.writeBytes(payload.data);
    }
}
