package org.artisanlogiciel.games.minetest.net;

import org.artisanlogiciel.games.minetest.core.PacketException;
import org.artisanlogiciel.games.minetest.core.Serialize;
import org.artisanlogiciel.games.minetest.core.v3s16;

import java.nio.ByteBuffer;

public class NetworkPacket {

    int m_protocol_id;
    int m_peer_id;
    int m_channel;
    public PacketType packetType;

    // somehow a BufferedPacket ...
    byte[] m_buffer; // m_data
    // used part in buffer
    int m_length; // m_datasize ?
    // current header index in packet
    int m_offset; // m_read_offset

    short m_command = 0;

    public NetworkPacket(int protocol_id, int peer_id, int channel, PacketType type, byte[] buffer, int length) {
        this.m_protocol_id = protocol_id;
        this.m_peer_id = peer_id;
        this.m_channel = channel;
        this.packetType = type;
        m_buffer = buffer;
        m_length = length;
        m_offset = 0;
    }

    public int getChannel()
    {
        return m_channel;
    }

    public byte[] getBuffer()
    {
        return m_buffer;
    }

    public int getOffset() {
        return m_offset;
    }

    public int getLength() {
        return m_length;
    }

    void addOffset(int offset)
    {
        m_offset += offset;
    }

    // Serialization
    public v3s16 v3s16()
            throws PacketException
    {
        return Serialize.readV3S16(m_buffer, m_offset, m_length);
    }

    public ByteBuffer getByteBuffer()
    {
        ByteBuffer buffer = ByteBuffer.wrap(m_buffer,m_offset,m_length-m_offset);
        return buffer;
    }
}
