package com.alterdekim.hearthhack.util;

import com.alterdekim.Protocol;
import lombok.Getter;
import lombok.Setter;

import java.io.ByteArrayOutputStream;

public class BattleNetPacket {

    private int headerSize = -1;

    private int bodySize = -1;

    @Getter
    @Setter
    private Protocol.Header header;

    @Getter
    @Setter
    private byte[] body;

    public BattleNetPacket(Protocol.Header header, byte[] body) {
        this.header = header;
        this.body = body;
    }

    public BattleNetPacket() {
        this.header = null;
        this.body = null;
    }

    public int Decode(byte[] bytes, int offset, int available) throws Exception {
        int num = 0;
        if (this.headerSize < 0) {
            if (available < 2) return num;
            this.headerSize = ((int)bytes[offset] << 8) + (int)bytes[offset + 1];
            available -= 2;
            num += 2;
            offset += 2;
        }
        if (this.header == null) {
            if (available < this.headerSize) return num;
            this.header = Protocol.Header.getDefaultInstance();
            byte[] s = new byte[this.headerSize];
            System.arraycopy(bytes, offset, s, 0, this.headerSize);
            this.header = Protocol.Header.parseFrom(s);
            this.bodySize = ((!this.header.hasSize()) ? 0 : this.header.getSize()); // something with unsigned integers (debug, if needed)
            available -= this.headerSize;
            num += this.headerSize;
            offset += this.headerSize;
        }
        if (this.body == null) {
            if (available < this.bodySize) return num;
            byte[] destinationArray = new byte[this.bodySize];
            System.arraycopy(bytes, offset, destinationArray, 0, this.bodySize);
            this.body = destinationArray;
            num += this.bodySize;
        }
        return num;
    }

    public byte[] Encode() throws Exception {
        int serializedSize = this.header.getSerializedSize();
        int serializedSize2 = this.body.length;
        byte[] array = new byte[2 + serializedSize + serializedSize2];
        array[0] = (byte)(serializedSize >> 8 & 255);
        array[1] = (byte)(serializedSize & 255);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        this.header.writeTo(baos);
        System.arraycopy(baos.toByteArray(), 0, array, 2, serializedSize);
        System.arraycopy(body, 0, array, 2 + serializedSize, serializedSize2);
        baos.close();
        return array;
    }
}
