package brn.swans.app.rtcp.msg;

import jist.runtime.Main;
import jist.swans.misc.Pickle;
import jist.swans.misc.Util;

/**
 * An RTCPByePacket is used to indicate that an rtp endsystem has left the
 * session. This implementation offers less functionality than described in the
 * rfc: Only one ssrc identifier can be stored in it and the reason for leaving
 * isn't transmitted.
 */
public class RtcpByeMessage extends RtcpMessage {

  // ////////////////////////////////////////////////
  // constants
  //

  // ////////////////////////////////////////////////
  // locals
  //

  /**
   * The ssrc identifier (unsigned).
   */
  protected int ssrc;

  // ////////////////////////////////////////////////
  // initialization
  //

  public RtcpByeMessage() {
    packetType = RTCP_PT_BYE;
    count = 1;
    ssrc = 0;

    // space for the ssrc identifier
    length += 4;
  }

  public RtcpByeMessage(byte[] msg, int offset) {
    super(msg, offset);

    if (Main.ASSERT)
      Util.assertion(RTCP_PT_BYE == packetType);

    // Bytes 4-7: ssrc
    ssrc = (int)Pickle.arrayToUInt(msg, offset + RtcpMessage.COMMON_HEADER_SIZE);
  }

  // ////////////////////////////////////////////////
  // accessors
  //

  public int getSsrc() {
    return ssrc;
  }

  public void setSsrc(int ssrc) {
    this.ssrc = ssrc;
  }

  // ////////////////////////////////////////////////
  // overwrites
  //

  public String toString() {
    return "RtcpByePacket [ssrc=" + ssrc + "]";
  }

  /*
   * (non-Javadoc)
   * @see brn.swans.app.rtcp.msg.RtcpMessage#getBytes(byte[], int)
   */
  public void getBytes(byte[] msg, int offset) {
    // Bytes 0-3: get the common header
    super.getCommonHeaderBytes(msg, offset);
    // Bytes 4-7: ssrc
    Pickle.uintToArray(ssrc, msg, offset + RtcpMessage.COMMON_HEADER_SIZE);
    // TODO reason code
  }

  /* (non-Javadoc)
   * @see java.lang.Object#hashCode()
   */
  public int hashCode() {
    final int PRIME = 31;
    int result = super.hashCode();
    result = PRIME * result + ssrc;
    return result;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#equals(java.lang.Object)
   */
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (!super.equals(obj))
      return false;
    if (getClass() != obj.getClass())
      return false;
    final RtcpByeMessage other = (RtcpByeMessage) obj;
    if (ssrc != other.ssrc)
      return false;
    return true;
  }
}
