Always return the replies sorted by time, oldest first.
[Sone.git] / src / main / java / net / pterodactylus / sone / data / Post.java
index 9887de9..33871c6 100644 (file)
 
 package net.pterodactylus.sone.data;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
 import java.util.UUID;
 
 /**
@@ -39,6 +45,9 @@ public class Post {
        /** The text of the post. */
        private final String text;
 
+       /** The replies that have been loaded for this post. */
+       private final Set<Reply> replies = new HashSet<Reply>();
+
        /**
         * Creates a new post.
         *
@@ -124,6 +133,49 @@ public class Post {
                return text;
        }
 
+       /**
+        * Returns all replies to this post in unspecified order.
+        *
+        * @return All replies to this post
+        */
+       public List<Reply> getReplies() {
+               List<Reply> sortedReplies = new ArrayList<Reply>(replies);
+               Collections.sort(sortedReplies, new Comparator<Reply>() {
+
+                       @Override
+                       public int compare(Reply leftReply, Reply rightReply) {
+                               return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
+                       }
+
+               });
+               return sortedReplies;
+       }
+
+       /**
+        * Adds a reply to this post. The reply will not be added if its
+        * {@link Reply#getPost() post} is not equal to this post.
+        *
+        * @param reply
+        *            The reply to add
+        */
+       public void addReply(Reply reply) {
+               if (reply.getPost().equals(this)) {
+                       replies.add(reply);
+               }
+       }
+
+       /**
+        * Removes a reply from this post.
+        *
+        * @param reply
+        *            The reply to remove
+        */
+       public void removeReply(Reply reply) {
+               if (reply.getPost().equals(this)) {
+                       replies.remove(reply);
+               }
+       }
+
        //
        // OBJECT METHODS
        //
@@ -133,7 +185,7 @@ public class Post {
         */
        @Override
        public int hashCode() {
-               return text.hashCode() ^ (int) (time >> 32) ^ (int) (time & 0xffffffff);
+               return id.hashCode() ^ sone.hashCode() ^ (int) (time >> 32) ^ (int) (time & 0xffffffff) ^ text.hashCode();
        }
 
        /**
@@ -144,7 +196,8 @@ public class Post {
                if (!(object instanceof Post)) {
                        return false;
                }
-               return ((Post) object).id.equals(id);
+               Post post = (Post) object;
+               return post.id.equals(id) && post.sone.equals(sone) && (post.time == time) && post.text.equals(text);
        }
 
 }