/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.buddyreplication;

import net.jcip.annotations.ThreadSafe;
import org.jboss.cache.util.ImmutableListCopy;
import org.jgroups.Address;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Vector;

/**
 * Value object that represents a buddy group
 *
 * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
 */
@ThreadSafe
public class BuddyGroup implements Serializable
{
   /**
    * Serial version.
    */
   private static final long serialVersionUID = 5391883716108410301L;

   private String groupName;

   private Address dataOwner;

   private Date lastModified = new Date();

   /**
    * List<Address> - a list of JGroups addresses
    */
   private final Vector<Address> buddies = new Vector<Address>();

   public String getGroupName()
   {
      return groupName;
   }

   protected void setGroupName(String groupName)
   {
      this.groupName = groupName;
      lastModified = new Date();
   }

   public Address getDataOwner()
   {
      return dataOwner;
   }

   protected void setDataOwner(Address dataOwner)
   {
      this.dataOwner = dataOwner;
      lastModified = new Date();
   }

   public List<Address> getBuddies()
   {
      // defensive copy and immutable.
      return new ImmutableListCopy<Address>(buddies);
   }

   protected void addBuddies(Collection<Address> buddies)
   {
      this.buddies.addAll(buddies);
      lastModified = new Date();
   }

   protected void removeBuddies(Collection<Address> buddies)
   {
      this.buddies.removeAll(buddies);
      lastModified = new Date();
   }

   public Date getLastModified()
   {
      return lastModified;
   }

   @Override
   public String toString()
   {
      StringBuilder b = new StringBuilder("BuddyGroup: (");
      b.append("dataOwner: ").append(dataOwner).append(", ");
      b.append("groupName: ").append(groupName).append(", ");
      b.append("buddies: ").append(buddies).append(",");
      b.append("lastModified: ").append(lastModified).append(")");
      return b.toString();
   }

   /**
    * Added in 2.2.0 as an optimisation for JGroups which internally uses vectors.
    *
    * @return a list of buddies
    * @since 2.2.0
    */
   public Vector<Address> getBuddiesAsVector()
   {
      return buddies;
   }
}
