/* Copyright (C) 2022 Free Software Foundation

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses>.  */


package org.gprofng.mpmt.ipc;

/**
 * <Header, RequestBody> where
 *
 * <p>Header: < HeaderMarker, RequestID, RequestType, ChannelID, nBytes/CancelRequestID/VersionID>
 *
 * <p>HeaderMarker (1 byte, value=255) RequestID: Unique numerical identifier generated by GUI -
 * positive integer - SIZE 4 bytes RequestType (INTEGER: enum SIZE 1 byte) o 0: Default: + Non-DBE
 * e.g. File Chooser, Remote Shell Command, Signal or + DBE e.g. Load Exp, Drop Exp, Get Data, Set
 * Filter o 1: Cancel o 2: Handshake ChannelID (INTEGER, SIZE 4 bytes) o 0: Non-DBE, or ignore in
 * case of Handshake requests o 1, 2, 3, ...: DBE nBytes: number of bytes in the request string.
 * (SIZE 4 bytes) OR CancelRequestID: For cancellation requests only, the ID of the request being
 * canceled. 0xFFFF for Cancel all requests OR VersionID: integer indicating version number in case
 * of Handshake requests
 *
 * <p>RequestBody:
 *
 * <p>RequestString: Body of the request itself (as a string).
 */
class IPCRequestHeader {
  private int requestID;
  private IPCHandle.RequestType requestType;
  private int channel;
  private int value; // nBytes in body (DEFAULT), cancelRequestID (CANCEL), version (HANDSHAKE)

  protected IPCRequestHeader(
      int requestID, IPCHandle.RequestType requestType, int channel, int value) {
    this.requestID = requestID;
    this.requestType = requestType;
    this.channel = channel;
    this.value = value;
  }

  protected String getBody() {
    StringBuilder buf = new StringBuilder();
    buf.append(sendByte(IPCProtocol.L_HEADER));
    buf.append(sendVal(requestID));
    buf.append(sendByte(requestType.index()));
    buf.append(sendVal(channel));
    buf.append(IPCProtocol.encodeVal(value));
    return buf.toString();
  }

  private String sendByte(final int b) {
    return IPCProtocol.encodeByte(b);
  }

  private String sendVal(final int i) {
    return IPCProtocol.encodeVal(i);
  }

  /**
   * @return the requestID
   */
  protected int getRequestID() {
    return requestID;
  }
}
