package jist.swans.mac;

import jist.swans.Constants;
import jist.swans.mac.MacMessage.AbstractMacMessage;
import jist.swans.misc.Message;
import jist.swans.misc.Pickle;

//////////////////////////////////////////////////
// messages
//

/**
 * MacDumbMessage is the packet sent out by the MacDumb mac.
 * <pre>
 *   src address:    size=6
 *   dst address:    size=6
 *   size:           size=2
 *   body:           0-65535
 * </pre>
 */
public class MacDumbMessage extends AbstractMacMessage 
  implements MacMessage, MacMessage.HasDst, MacMessage.HasSrc, MacMessage.HasBody
{
  /** fixed mac packet header length. */
  public static int HEADER_SIZE = 14;

  /** mac message source address. */
  private MacAddress src;
  /** mac message destination address. */
  private MacAddress dst;
  /** mac message payload. */
  private Message body;

  /**
   * Create new mac packet.
   *
   * @param src source mac address
   * @param dst destination mac address
   * @param body mac packet payload
   */
  public MacDumbMessage(MacAddress src, MacAddress dst, Message body)
  {
    this.src = src;
    this.dst = dst;
    this.body = body;
  }

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

  /**
   * Return mac message source.
   *
   * @return mac message source
   */
  public MacAddress getSrc()
  {
    return src;
  }

  /**
   * Return mac message destination.
   *
   * @return mac message destination
   */
  public MacAddress getDst()
  {
    return dst;
  }

  /**
   * Return mac message payload.
   *
   * @return mac message payload
   */
  public Message getPayload()
  {
    return body;
  }

  public Message getBody()
  {
    return body;
  }

  //////////////////////////////////////////////////
  // message interface
  //

  /** {@inheritDoc} */
  public int getSize()
  {
    int size = body.getSize();
    if(size==Constants.ZERO_WIRE_SIZE)
    {
      return Constants.ZERO_WIRE_SIZE;
    }
    return HEADER_SIZE+size;
  }

  /** {@inheritDoc} */
  public void getBytes(byte[] msg, int offset)
  {
    // 0-5: da
    Pickle.MacAddressToArray(dst, msg, offset + 0);
    // 6-11: sa
    Pickle.MacAddressToArray(src, msg, offset + 6);
    // 12-13: ethertype
    Pickle.ushortToArray(0x0800, msg, offset + 12);
    
    body.getBytes(msg, offset + 14);
  }

  /** {@inheritDoc} */
  public String toString()
  {
    return "macdumb(payload="+body+")";
  }

  public Object getAdapter(Class adapter) {
    if (adapter.equals(MacMessage.HasSrc.class))
      return this;
    if (adapter.equals(MacMessage.HasDst.class))
      return this;
    if (adapter.equals(MacMessage.HasBody.class))
      return this;
    return null;
  }
} // class: MacDumbMessage
