package org.jboss.cache.buddyreplication;

import org.jgroups.Address;
import org.jgroups.Channel;
import org.jgroups.Event;
import org.jgroups.stack.IpAddress;

import java.lang.reflect.Field;
import java.net.InetAddress;

/**
 * An address locator that is able to deal with the JGroups 2.8 PhysicalAddress interface
 *
 * @author Manik Surtani
 * @since 3.2.0
 */
public class JGroups28AddressLocator extends JGroups26AddressLocator
{
   int getPhysicalAddressEventId;

   public JGroups28AddressLocator() {
      try {
         Class eventClass = Event.class;
         Field f = eventClass.getField("GET_PHYSICAL_ADDRESS");
         getPhysicalAddressEventId = (Integer) f.get(null);
      } catch (Exception e) {
         throw new RuntimeException("Unable to initialize AddressLocator", e);
      }
   }

   @Override
   public InetAddress locate(Channel channel, Address a)
   {
      if (a instanceof IpAddress)
      {
         return super.locate(channel, a);
      }
      else
      {
         Address physicalAddress = (Address) channel.downcall(new Event(getPhysicalAddressEventId, a));
         return super.locate(channel, physicalAddress);
      }
   }
}
