package xyz.tbvns.rogue_block.Packets;

import com.esotericsoftware.kryo.kryo5.Kryo;
import com.esotericsoftware.kryo.kryo5.io.Input;
import com.esotericsoftware.kryo.kryo5.io.Output;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.server.network.ServerPlayerEntity;
import xyz.tbvns.rogue_block.Managers.registeredSavable.PlayerData;
import xyz.tbvns.rogue_block.Packets.registeredPackets.BytesPacket;

import java.nio.ByteBuffer;

public class PacketManager {
    static Kryo kryo = new Kryo();
    public static void setup() {
        kryo.setRegistrationRequired(false);
    }

    public static PlayerData readPlayerData(byte[] buffer) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, 1000);
        buffer = byteBuffer.array();
        Input input = new Input(buffer);
        PlayerData packet = kryo.readObject(input, PlayerData.class);
        input.close();
        return packet;
    }

    public static ByteBuffer writeUpgradePacket(PlayerData object) {
        Output output = new Output(1000);
        kryo.writeObject(output, object);
        ByteBuffer buffer = ByteBuffer.wrap(output.getBuffer());
        output.close();
        return buffer;
    }

    public static void sendUpgradePacket(ServerPlayerEntity entity, PlayerData data) {
        BytesPacket packet = new BytesPacket(writeUpgradePacket(data).array());
        entity.server.execute(() -> {
            ServerPlayNetworking.send(entity, packet);
        });
    }
}
