package org.jboss.cache.marshall;

import org.jboss.cache.Fqn;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Map;

/**
 * Serializable representation of the data of a node (FQN and attributes)
 *
 * @author Bela Ban
 * @version $Id: NodeData.java 5723 2008-04-28 14:53:03Z manik.surtani@jboss.com $
 */
// TODO: 3.0.0: remove Externalizable and rely on the CacheMarshaller.
public class NodeData implements Externalizable
{
   private Fqn<?> fqn = null;
   private Map<?, ?> attrs = null;

   static final long serialVersionUID = -7571995794010294485L;

   public NodeData()
   {
   }

   public NodeData(Fqn<?> fqn)
   {
      this.fqn = fqn;
   }

   public NodeData(Fqn<?> fqn, Map<?, ?> attrs)
   {
      this.fqn = fqn;
      this.attrs = attrs;
   }

   public NodeData(String fqn, Map<?, ?> attrs)
   {
      this.fqn = Fqn.fromString(fqn);
      this.attrs = attrs;
   }

   public Map getAttributes()
   {
      return attrs;
   }

   public Fqn getFqn()
   {
      return fqn;
   }

   public boolean isMarker()
   {
      return false;
   }

   public boolean isExceptionMarker()
   {
      return false;
   }

   // TODO: 3.0.0: Remove and replace with marshallNodeData/unmarshallNodeData methods in the CacheMarshaller so that we can use the same marshalling framework for Fqns.
   public void writeExternal(ObjectOutput out) throws IOException
   {
      out.writeObject(fqn);
      if (attrs != null)
      {
         out.writeBoolean(true);
         out.writeObject(attrs);
      }
      else
      {
         out.writeBoolean(false);
      }
   }

   // TODO: 3.0.0: Remove in and replace with marshallNodeData/unmarshallNodeData methods in the CacheMarshaller so that we can use the same marshalling framework for Fqns.
   @SuppressWarnings("unchecked")
   public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
   {
      fqn = (Fqn) in.readObject();
      if (in.readBoolean())
      {
         attrs = (Map) in.readObject();
      }
   }

   @Override
   public String toString()
   {
      return "NodeData {fqn: " + fqn + ", attrs=" + attrs + "}";
   }


   @Override
   public boolean equals(Object o)
   {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      NodeData nodeData = (NodeData) o;

      if (attrs != null ? !attrs.equals(nodeData.attrs) : nodeData.attrs != null) return false;
      if (fqn != null ? !fqn.equals(nodeData.fqn) : nodeData.fqn != null) return false;

      return true;
   }

   @Override
   public int hashCode()
   {
      int result;
      result = (fqn != null ? fqn.hashCode() : 0);
      result = 31 * result + (attrs != null ? attrs.hashCode() : 0);
      return result;
   }
}
