package com.alterdekim.hearthhack.util;

import com.alterdekim.Protocol;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

public class ClientRequestManager {


    // Rewritten method from hearthstone source code
    public static byte[] GetUtilPacketBytes( ClientRequestBody body ) {
        Protocol.RpcHeader.Builder rpcHeader = Protocol.RpcHeader.newBuilder();
        rpcHeader.setType(body.getType()); // (ulong)
        if (body.getSendCount() > 0) rpcHeader.setRetryCount(body.getSendCount()); // (ulong)
        Protocol.RpcMessage.Builder rpcMessage = Protocol.RpcMessage.newBuilder();
        rpcMessage.setRpcHeader(rpcHeader);
        if (body.getBody() != null && body.getBody().length > 0) rpcMessage.setMessageBody(ByteString.copyFrom(body.getBody()));
        return rpcMessage.build().toByteArray();
    }

    // Inverted GetUtilPacketBytes method
    public static ClientRequestBody GetUtilPacketFromBytes( byte[] data ) throws InvalidProtocolBufferException {
        Protocol.RpcMessage rpcMessage = Protocol.RpcMessage.parseFrom(data);
        ClientRequestBody body = new ClientRequestBody();
        body.setBody(rpcMessage.getMessageBody().toByteArray());
        body.setType((int) rpcMessage.getRpcHeader().getType());
        body.setSendCount((int)rpcMessage.getRpcHeader().getRetryCount());
        return body;
    }
}
