package click.swans.mac;

import jist.swans.mac.MacAddress;
import jist.swans.mac.MacDumbMessage;
import jist.swans.mac.MacDumbMessageFactory;
import jist.swans.mac.MacMessage;
import jist.swans.misc.Message;
import jist.swans.misc.MessageBytes;
import jist.swans.misc.Pickle;
import jist.swans.net.NetMessage;
import jist.swans.Constants;

public class MacDumbClickMessageFactory extends MacDumbMessageFactory{

  public MacMessage fromBytes(byte[] msg, int offset) throws Message.IllegalFormatException {
    // 0-5: da
    MacAddress dst = new MacAddress(msg, offset + 0);
    // 5-11: sa
    MacAddress src = new MacAddress(msg, offset + 6);
    // 12-13: ethertype
    int etherType = Pickle.arrayToUShort(msg, offset + 12);
    // payload
    Message body;
    switch (etherType) {
    case Constants.MAC_ETHERTYPE_IP:
      body = new NetMessage.Ip(msg, offset + 14);
      break;
    case Constants.MAC_ETHERTYPE_BRN:
   case Constants.MAC_ETHERTYPE_ARP:
    default:
      body = new MessageBytes(msg, offset + 14, msg.length - offset - 14);
      break;
    }
    
    return new MacDumbMessage(src, dst, body);
  }

  public Message getPayload(MacMessage msg) {
    return msg;
  }

  public MacDumbMessage createData(MacAddress src, MacAddress dst, Message body) {
    if (body instanceof MacDumbMessage)
      return (MacDumbMessage) body;
    return new MacDumbMessage(src,dst,body);
  }

}
