package com.simpletwitter.service;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.simpletwitter.common.DatabaseManager;
import com.simpletwitter.common.SimpleTwitterCriteria;
import com.simpletwitter.common.SimpleTwitterCriterion;
import com.simpletwitter.models.Tweet;
import com.simpletwitter.models.TwitterUser;
public class TweetService {
public static Tweet createTweet(Tweet tweet) {
DatabaseManager da = DatabaseManager.getInstance();
return da.createObject(tweet);
}
public static Set<Tweet> getTweets(Long userId) {
DatabaseManager da = DatabaseManager.getInstance();
List<Tweet> tweetList = da.getChildrenForParent(userId,
TwitterUser.class, Tweet.class);
Collections.sort(tweetList, new Comparator<Tweet>() {
@Override
public int compare(Tweet o1, Tweet o2) {
return o2.getDateCreated().compareTo(o1.getDateCreated());
}
});
HashSet<Tweet> stream = new LinkedHashSet<Tweet>(tweetList);
return stream;
}
public static Set<Tweet> getTweetStream(Long userId,
Set<TwitterUser> followingIds) {
DatabaseManager da = DatabaseManager.getInstance();
SimpleTwitterCriteria criteria = SimpleTwitterCriteria.instance();
SimpleTwitterCriterion[] criterionList = new SimpleTwitterCriterion[(followingIds
.size() + 1)];
criterionList[0] = SimpleTwitterCriterion.eq("twitterUser.objId",
userId);
int i = 1;
for (TwitterUser fuser : followingIds) {
criterionList[i] = SimpleTwitterCriterion.eq("twitterUser.objId",
fuser.getObjId());
i++;
}
criteria.add(SimpleTwitterCriterion.or(criterionList));
List<Tweet> allObjects = da.getAllObjects(Tweet.class, criteria);
Collections.sort(allObjects, new Comparator<Tweet>() {
@Override
public int compare(Tweet o1, Tweet o2) {
return o2.getDateCreated().compareTo(o1.getDateCreated());
}
});
HashSet<Tweet> stream = new LinkedHashSet<Tweet>(allObjects);
return stream;
}
public static Tweet getTweet(Long objId) {
DatabaseManager da = DatabaseManager.getInstance();
return da.getObject(Tweet.class, objId);
}
public static void deleteTweet(Tweet tweet) {
DatabaseManager da = DatabaseManager.getInstance();
da.deleteObject(tweet);
}
}