/*************************************************************************

"FreePastry" Peer-to-Peer Application Development Substrate 

Copyright 2002, Rice University. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

- Neither  the name  of Rice  University (RICE) nor  the names  of its
contributors may be  used to endorse or promote  products derived from
this software without specific prior written permission.

This software is provided by RICE and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall RICE or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

********************************************************************************/
package rice.pastry.routing;

import rice.p2p.commonapi.rawserialization.*;

import rice.pastry.*;
import rice.pastry.commonapi.PastryEndpointMessage;
import rice.pastry.messaging.*;

import java.io.*;

/**
 * A route message contains a pastry message that has been wrapped to be sent to
 * another pastry node.
 *
 * @version $Id: RouteMessage.java 3300 2006-06-09 09:28:36Z jeffh $
 * @author Andrew Ladd
 */

public class RouteMessage extends PRawMessage implements
      rice.p2p.commonapi.RouteMessage, Serializable {

  private Id target;

  private NodeHandle prevNode;

  private transient SendOptions opts;

  private int auxAddress;

  /**
   * DESCRIBE THE FIELD
   */
  public transient NodeHandle nextHop;

  private Message internalMsg;
  // optimization to not use instanceof in the normal new case
  private PRawMessage rawInternalMsg = null;
  private InputBuffer serializedMsg;
  private NodeHandleFactory nhf;
  PastryNode pn;

  boolean hasSender;
  byte internalPriority;

  private RMDeserializer endpointDeserializer = new RMDeserializer();
  private static final long serialVersionUID = 3492981895989180093L;

  /**
   * DESCRIBE THE FIELD
   */
  public static final short TYPE = -23525;

  /**
   * Constructor.
   *
   * @param target this is id of the node the message will be routed to.
   * @param msg the wrapped message.
   */

  public RouteMessage(Id target, Message msg) {
    this(target, msg, null, null);
  }

  /**
   * Constructor.
   *
   * @param target this is id of the node the message will be routed to.
   * @param msg the wrapped message.
   * @param opts the send options for the message.
   */

  public RouteMessage(Id target, Message msg, SendOptions opts) {
    this(target, msg, null, opts);
  }

  /**
   * Constructor.
   *
   * @param dest the node this message will be routed to
   * @param msg the wrapped message.
   * @param opts the send options for the message.
   */

  public RouteMessage(NodeHandle dest, Message msg,
        SendOptions opts) {
    this(dest.getNodeId(), msg, dest, opts);
  }

  /**
   * Constructor.
   *
   * @param target this is id of the node the message will be routed to.
   * @param msg the wrapped message.
   * @param firstHop the nodeHandle of the first hop destination
   */
  public RouteMessage(Id target, Message msg, NodeHandle firstHop) {
    this(target, msg, firstHop, null);
  }

  /**
   * Constructor for RouteMessage.
   *
   * @param target DESCRIBE THE PARAMETER
   * @param msg DESCRIBE THE PARAMETER
   * @param firstHop DESCRIBE THE PARAMETER
   * @param opts DESCRIBE THE PARAMETER
   */
  public RouteMessage(Id target, PRawMessage msg, NodeHandle firstHop, SendOptions opts) {
    this(target, (Message) msg, firstHop, opts);
    rawInternalMsg = msg;
  }

  /**
   * Constructor.
   *
   * @param target this is id of the node the message will be routed to.
   * @param msg the wrapped message.
   * @param firstHop the nodeHandle of the first hop destination
   * @param opts the send options for the message.
   */
  public RouteMessage(Id target, Message msg, NodeHandle firstHop, SendOptions opts) {
    super(RouterAddress.getCode());
    this.target = (Id) target;
    internalMsg = msg;
    nextHop = firstHop;
    this.opts = opts;
    if (this.opts == null) {
      this.opts = new SendOptions();
    }
    if (msg != null) {
      // can be null on the deserialization, but that ctor properly sets auxAddress
      auxAddress = msg.getDestination();
    }
  }

  /**
   * Constructor for RouteMessage.
   *
   * @param target DESCRIBE THE PARAMETER
   * @param auxAddress DESCRIBE THE PARAMETER
   * @param prev DESCRIBE THE PARAMETER
   * @param buf DESCRIBE THE PARAMETER
   * @param nhf DESCRIBE THE PARAMETER
   * @param pn DESCRIBE THE PARAMETER
   * @exception IOException DESCRIBE THE EXCEPTION
   */
  public RouteMessage(Id target, int auxAddress, NodeHandle prev, InputBuffer buf, NodeHandleFactory nhf, PastryNode pn) throws IOException {
    this(target, null, null, null);
    hasSender = buf.readBoolean();
    internalPriority = buf.readByte();
    prevNode = prev;
    serializedMsg = buf;
    this.nhf = nhf;
    this.pn = pn;
    this.auxAddress = auxAddress;
  }

  /**
   * Gets the target node id of this message.
   *
   * @return the target node id.
   */

  public Id getTarget() {
    return target;
  }

  /**
   * Gets the PrevNode attribute of the RouteMessage object
   *
   * @return The PrevNode value
   */
  public NodeHandle getPrevNode() {
    return prevNode;
  }

  /**
   * Gets the NextHop attribute of the RouteMessage object
   *
   * @return The NextHop value
   */
  public NodeHandle getNextHop() {
    return nextHop;
  }

  /**
   * Get priority
   *
   * @return the priority of this message.
   */

  public byte getPriority() {
    if (internalMsg != null) {
      return internalMsg.getPriority();
    }
    return internalPriority;
  }

  /**
   * Get receiver address.
   *
   * @return the address.
   */

  public int getDestination() {
    if (nextHop == null || auxAddress == 0) {
      return super.getDestination();
    }

    return auxAddress;
  }

  /**
   * Get transmission options.
   *
   * @return the options.
   */

  public SendOptions getOptions() {
    if (opts == null) {
      opts = new SendOptions();
    }
    return opts;
  }

  // Common API Support

  /**
   * Gets the DestinationId attribute of the RouteMessage object
   *
   * @return The DestinationId value
   */
  public rice.p2p.commonapi.Id getDestinationId() {
    return getTarget();
  }

  /**
   * Gets the NextHopHandle attribute of the RouteMessage object
   *
   * @return The NextHopHandle value
   */
  public rice.p2p.commonapi.NodeHandle getNextHopHandle() {
    return nextHop;
  }

  /**
   * Gets the Message attribute of the RouteMessage object
   *
   * @return The Message value
   */
  public rice.p2p.commonapi.Message getMessage() {
    return ((PastryEndpointMessage) unwrap()).getMessage();
  }

  /**
   * Gets the Message attribute of the RouteMessage object
   *
   * @param md DESCRIBE THE PARAMETER
   * @return The Message value
   * @exception IOException DESCRIBE THE EXCEPTION
   */
  public rice.p2p.commonapi.Message getMessage(MessageDeserializer md) throws IOException {
    endpointDeserializer.setSubDeserializer(md);
    return ((PastryEndpointMessage) unwrap(endpointDeserializer)).getMessage();
  }

  /**
   * Gets the Type attribute of the RouteMessage object
   *
   * @return The Type value
   */
  public short getType() {
    return TYPE;
  }

  /**
   * Gets the AuxAddress attribute of the RouteMessage object
   *
   * @return The AuxAddress value
   */
  public int getAuxAddress() {
    return auxAddress;
  }

  /**
   * Gets the InternalType attribute of the RouteMessage object
   *
   * @return The InternalType value
   */
  public short getInternalType() {
    if (rawInternalMsg != null) {
      return rawInternalMsg.getType();
    }
    if (internalMsg != null) {
      if (internalMsg instanceof RawMessage) {
        return ((RawMessage) internalMsg).getType();
      }
      return 0;
    }
    return -1;
  }

  /**
   * Sets the PrevNode attribute of the RouteMessage object
   *
   * @param n The new PrevNode value
   */
  public void setPrevNode(NodeHandle n) {
    prevNode = n;
  }

  /**
   * Sets the NextHop attribute of the RouteMessage object
   *
   * @param nh The new NextHop value
   */
  public void setNextHop(NodeHandle nh) {
    nextHop = nh;
  }

  /**
   * Sets the DestinationId attribute of the RouteMessage object
   *
   * @param id The new DestinationId value
   */
  public void setDestinationId(rice.p2p.commonapi.Id id) {
    target = (Id) id;
  }

  /**
   * Sets the NextHopHandle attribute of the RouteMessage object
   *
   * @param nextHop The new NextHopHandle value
   */
  public void setNextHopHandle(rice.p2p.commonapi.NodeHandle nextHop) {
    this.nextHop = (NodeHandle) nextHop;
  }

  /**
   * Sets the Message attribute of the RouteMessage object
   *
   * @param message The new Message value
   */
  public void setMessage(rice.p2p.commonapi.Message message) {
    ((PastryEndpointMessage) unwrap()).setMessage(message);
  }

  /**
   * Sets the Message attribute of the RouteMessage object
   *
   * @param message The new Message value
   */
  public void setMessage(RawMessage message) {
    ((PastryEndpointMessage) unwrap()).setMessage(message);
  }



  /**
   * Routes the messages if the next hop has been set up.
   *
   * @param localHandle DESCRIBE THE PARAMETER
   * @return true if the message got routed, false otherwise.
   */

  public boolean routeMessage(NodeHandle localHandle) {
    if (nextHop == null) {
      return false;
    }
    setSender(localHandle);

    NodeHandle handle = nextHop;
    nextHop = null;
    prevNode = localHandle;

    if (localHandle.equals(handle)) {
      localHandle.getLocalNode().send(handle, internalMsg);
    } else {
      localHandle.getLocalNode().send(handle, this);
    }

    return true;
  }

  /**
   * The wrapped message.
   *
   * @return the wrapped message.
   * @deprecated use unwrap(MessageDeserializer)
   */
  public Message unwrap() {
    if (internalMsg != null) {
      return internalMsg;
    }
    try {
      endpointDeserializer.setSubDeserializer(endpointDeserializer);
      return unwrap(endpointDeserializer);
      //pn.getEnvironment().getLogManager().getLogger(RouteMessage.class, null)));
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }

  /**
   * Converts to a String representation of the object.
   *
   * @return A string representation of the object.
   */
  public String toString() {
    String str = "";
    str += "[ " + internalMsg + " ]";

    return str;
  }

  /**
   * DESCRIBE THE METHOD
   *
   * @param buf DESCRIBE THE PARAMETER
   * @exception IOException DESCRIBE THE EXCEPTION
   */
  public void serialize(OutputBuffer buf) throws IOException {
    buf.writeByte((byte) 0);
    // version
    buf.writeInt(auxAddress);
    target.serialize(buf);
    prevNode.serialize(buf);
    if (serializedMsg != null) {
      // optimize this, possibly by extending InternalBuffer interface to access the raw underlieing bytes
      byte[] raw = new byte[serializedMsg.bytesRemaining()];
      serializedMsg.read(raw);
      buf.write(raw, 0, raw.length);
      serializedMsg = null;
      // note, this leaves the RouteMessage in a busted state no rawInternalMsg, internalMsg, serializedMsg
    } else {
      if (rawInternalMsg == null) {
        rawInternalMsg = convert(internalMsg);
      }
//    address was already peeled off as the auxAddress
//    different wire to deserialize the Address and eliminate unneeded junk
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    +bool hasSender +   Priority    +  Type (Application specifc)   + // zero is java serialization
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//    optional
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    +            NodeHandle sender                                  +
//    +                                                               +
//                      ...  flexable size
//    +                                                               +
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      NodeHandle sender = rawInternalMsg.getSender();
      boolean hasSender = (sender != null);
      if (hasSender) {
        buf.writeBoolean(true);
      } else {
        buf.writeBoolean(false);
      }
      buf.writeByte(rawInternalMsg.getPriority());
      buf.writeShort(rawInternalMsg.getType());

      if (hasSender) {
        sender.serialize(buf);
      }

      rawInternalMsg.serialize(buf);
    }
  }

  /**
   * DESCRIBE THE METHOD
   *
   * @param md DESCRIBE THE PARAMETER
   * @return DESCRIBE THE RETURN VALUE
   * @exception IOException DESCRIBE THE EXCEPTION
   */
  public Message unwrap(MessageDeserializer md) throws IOException {
    if (internalMsg != null) {
      return internalMsg;
    }
//
//      if (internalMsg.getType() == 0) {
//        PJavaSerializedMessage pjsm = (PJavaSerializedMessage)internalMsg;
//        return pjsm.getMessage();
//      }
//      return internalMsg;
//    }

    // deserialize using md

//  address was already peeled off as the auxAddress
//  different wire to deserialize the Address and eliminate unneeded junk
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  +bool hasSender +   Priority    +  Type (Application specifc)   + // zero is java serialization
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//  optional
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  +            NodeHandle sender                                  +
//  +                                                               +
//                    ...  flexable size
//  +                                                               +
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

    NodeHandle internalSender = null;
    short internalType = serializedMsg.readShort();
    if (hasSender) {
      internalSender = nhf.readNodeHandle(serializedMsg);
    }

    internalMsg = (Message) md.deserialize(serializedMsg, internalType, internalPriority, internalSender);

    // the serializedMsg is now dirty, because the unwrapper may change the internal message
    serializedMsg = null;
    nhf = null;

    return internalMsg;
  }

  /**
   * DESCRIBE THE METHOD
   *
   * @param msg DESCRIBE THE PARAMETER
   * @return DESCRIBE THE RETURN VALUE
   */
  private static PRawMessage convert(Message msg) {
    if (msg instanceof PRawMessage) {
      PRawMessage prm = (PRawMessage) msg;
      if (prm.getType() == 0) {
        throw new RuntimeException("Cannot route a PJavaSerializedMessage, this is used internally in RouteMessage.");
      }
      return prm;
    }
    return new PJavaSerializedMessage(msg);
  }

  /**
   * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + int
   * auxAddress + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   * + Id target + + + + + + + + + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   * + NodeHandle prev + + (used to repair routing table during routing) + + +
   * ... + + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
   * Internal Message + + (see below) + + +
   *
   * @param buf
   * @param nhf DESCRIBE THE PARAMETER
   * @param pn DESCRIBE THE PARAMETER
   * @return
   * @exception IOException DESCRIBE THE EXCEPTION
   */
  public static RouteMessage build(InputBuffer buf, NodeHandleFactory nhf, PastryNode pn) throws IOException {

    byte version = buf.readByte();
    switch (version) {
      case 0:
        int auxAddress = buf.readInt();
        Id target = Id.build(buf);
        NodeHandle prev = nhf.readNodeHandle(buf);
        return new RouteMessage(target, auxAddress, prev, buf, nhf, pn);
      default:
        throw new IOException("Unknown Version: " + version);
    }
  }

  /**
   * DESCRIBE THE CLASS
   *
   * @version $Id: pretty.settings 2305 2005-03-11 20:22:33Z jeffh $
   * @author jeffh
   */
  class RMDeserializer extends PJavaSerializedDeserializer {
    MessageDeserializer sub;

    /**
     * Constructor for RMDeserializer.
     */
    public RMDeserializer() {
      // the late binding of pn is pretty problematic, we'll set it right before we deserialize
      // the thing is, we usually won't even need it
      super(null);
    }

    /**
     * Sets the SubDeserializer attribute of the RMDeserializer object
     *
     * @param md The new SubDeserializer value
     */
    public void setSubDeserializer(MessageDeserializer md) {
      sub = md;
    }

    /**
     * DESCRIBE THE METHOD
     *
     * @param buf DESCRIBE THE PARAMETER
     * @param type DESCRIBE THE PARAMETER
     * @param priority DESCRIBE THE PARAMETER
     * @param sender DESCRIBE THE PARAMETER
     * @return DESCRIBE THE RETURN VALUE
     * @exception IOException DESCRIBE THE EXCEPTION
     */
    public Message deserialize(InputBuffer buf, short type, byte priority, NodeHandle sender) throws IOException {
      // just in case we have to do java serialization
      pn = RouteMessage.this.pn;
      switch (type) {
        case PastryEndpointMessage.TYPE:
          return new PastryEndpointMessage(auxAddress, buf, sub, sender);
      }
      return null;
    }

  }

}
