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

"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.standard;

import rice.environment.Environment;
import rice.environment.logging.Logger;
import rice.p2p.commonapi.rawserialization.*;
import rice.pastry.*;
import rice.pastry.client.PastryAppl;
import rice.pastry.messaging.*;
import rice.pastry.routing.*;

import java.io.IOException;
import java.util.*;

/**
 * An implementation of a simple route set protocol.
 *
 * @version $Id: StandardRouteSetProtocol.java,v 1.15 2005/03/11 00:58:02 jeffh
 *      Exp $
 * @author Andrew Ladd
 * @author Peter Druschel
 */

public class StandardRouteSetProtocol extends PastryAppl {
  private final int maxTrials;

  private RoutingTable routeTable;

  private Environment environmet;

  /**
   * DESCRIBE THE FIELD
   */
  protected Logger logger;

  /**
   * Constructor.
   *
   * @param rt the routing table
   * @param ln DESCRIBE THE PARAMETER
   * @param env DESCRIBE THE PARAMETER
   */
  public StandardRouteSetProtocol(PastryNode ln, RoutingTable rt, Environment env) {
    this(ln, rt, env, null);
  }

  /**
   * Constructor for StandardRouteSetProtocol.
   *
   * @param ln DESCRIBE THE PARAMETER
   * @param rt DESCRIBE THE PARAMETER
   * @param env DESCRIBE THE PARAMETER
   * @param md DESCRIBE THE PARAMETER
   */
  public StandardRouteSetProtocol(PastryNode ln, RoutingTable rt, Environment env, MessageDeserializer md) {
    super(ln, null, RouteProtocolAddress.getCode(), md == null ? new SRSPDeserializer(ln) : md);
    this.environmet = env;
    maxTrials = (1 << rt.baseBitLength()) / 2;
    routeTable = rt;
    logger = env.getLogManager().getLogger(getClass(), null);
  }

  /**
   * Receives a message.
   *
   * @param msg the message.
   */

  public void messageForAppl(Message msg) {
    if (msg instanceof BroadcastRouteRow) {
      BroadcastRouteRow brr = (BroadcastRouteRow) msg;

      RouteSet[] row = brr.getRow();

      NodeHandle nh = brr.from();
      if (nh.isAlive()) {
        routeTable.put(nh);
      }

      for (int i = 0; i < row.length; i++) {
        RouteSet rs = row[i];

        for (int j = 0; rs != null && j < rs.size(); j++) {
          nh = rs.get(j);
          if (nh.isAlive() == false) {
            continue;
          }
          routeTable.put(nh);
        }
      }
    } else if (msg instanceof RequestRouteRow) {
      // a remote node request one of
      // our routeTable rows
      RequestRouteRow rrr = (RequestRouteRow) msg;

      int reqRow = rrr.getRow();
      NodeHandle nh = rrr.returnHandle();

      RouteSet row[] = routeTable.getRow(reqRow);
      BroadcastRouteRow brr = new BroadcastRouteRow(thePastryNode.getLocalHandle(), row);
      nh.receiveMessage(brr);
    } else if (msg instanceof InitiateRouteSetMaintenance) {
      // request for
      // routing table
      // maintenance

      // perform routing table maintenance
      maintainRouteSet();

    } else {
      throw new Error(
        "StandardRouteSetProtocol: received message is of unknown type");
    }

  }

  /**
   * performs periodic maintenance of the routing table for each populated row
   * of the routing table, it picks a random column and swaps routing table rows
   * with the closest entry in that column
   */

  private void maintainRouteSet() {

    if (logger.level <= Logger.FINE) {
      logger.log(
        "maintainRouteSet " + thePastryNode.getLocalHandle().getNodeId());
    }

    // for each populated row in our routing table
    for (byte i = (byte) (routeTable.numRows() - 1); i >= 0; i--) {
      RouteSet row[] = routeTable.getRow(i);
      BroadcastRouteRow brr = new BroadcastRouteRow(thePastryNode.getLocalHandle(), row);
      RequestRouteRow rrr = new RequestRouteRow(thePastryNode.getLocalHandle(), i);
      int myCol = thePastryNode.getLocalHandle().getNodeId().getDigit(i,
        routeTable.baseBitLength());
      int j;

      // try up to maxTrials times to find a column with live entries
      for (j = 0; j < maxTrials; j++) {
        // pick a random column
        int col = environmet.getRandomSource().nextInt(routeTable.numColumns());
        if (col == myCol) {
          continue;
        }

        RouteSet rs = row[col];

        // swap row with closest node only
        NodeHandle nh;

        if (rs != null && (nh = rs.closestNode()) != null) {
          nh.receiveMessage(brr);
          nh.receiveMessage(rrr);
          break;
        }
      }

      // once we hit a row where we can't find a populated entry after numTrial
      // trials, we finish
      if (j == maxTrials) {
        break;
      }
    }

  }

  /**
   * DESCRIBE THE METHOD
   *
   * @return DESCRIBE THE RETURN VALUE
   */
  public boolean deliverWhenNotReady() {
    return true;
  }

  /**
   * DESCRIBE THE CLASS
   *
   * @version $Id: pretty.settings 2305 2005-03-11 20:22:33Z jeffh $
   * @author jeffh
   */
  static class SRSPDeserializer extends PJavaSerializedDeserializer {
    /**
     * Constructor for SRSPDeserializer.
     *
     * @param pn DESCRIBE THE PARAMETER
     */
    public SRSPDeserializer(PastryNode pn) {
      super(pn);
    }

    /**
     * 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 {
      switch (type) {
        case RequestRouteRow.TYPE:
          return new RequestRouteRow(sender, buf);
        case BroadcastRouteRow.TYPE:
          return new BroadcastRouteRow(buf, pn);
      }
      return null;
    }
  }

}
