package main;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;

import twitter4j.Trend;
import twitter4j.Trends;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

public class MongoDB {

	MongoClient mongoClient;

	ArrayList<Trend> oldTrends;

	public MongoDB() {

		try {

			mongoClient = new MongoClient("localhost");

		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		oldTrends = new ArrayList<>();

	}

	public void addTrend(Trends trends) {

		Date now = new Date();

		DB db = mongoClient.getDB("twitter");

		DBCollection coll = db.getCollection("trends");

		for (Trend t : trends.getTrends()) {
			System.out.println(t.getName());
			coll.insert(new BasicDBObject("name", t.getName()).append("arrival", now).append("withdrawal", "not-finished"));
		}

		if (!oldTrends.isEmpty()) {
			for (Trend old : oldTrends) {
				for (Trend t : trends.getTrends()) {
					if (old.getName().compareTo(t.getName()) == 0) {

						BasicDBObject newDocument = new BasicDBObject();
						newDocument.append("$set", new BasicDBObject().append("withdrawal", now));

						BasicDBObject searchQuery = new BasicDBObject().append("name", old.getName());

						coll.update(searchQuery, newDocument);
						break;
					}

				}
			}
		}

		oldTrends.clear();
		for (Trend t : trends.getTrends()) {
			oldTrends.add(t);

		}

	}
}

@@ -269,16 +269,51 @@
 oClient;
+%0Aimport com.mongodb.MongoException;
 %0A%0Apublic
@@ -565,24 +565,206 @@
 ace();%0A%09%09%7D%0A%0A
+%09%09DB db = mongoClient.getDB(%22twitter%22);%0A%0A%09%09DBCollection coll = db.getCollection(%22trends%22);%0A%09%09%0A%09%09coll.createIndex(new BasicDBObject(%22name%22, 1), new BasicDBObject(%22unique%22, true));%0A%09%09%0A
 %09%09oldTrends 
@@ -854,17 +854,22 @@
 Date();%0A
+%09%09%0A%09%09
 %0A
-
 %09%09DB db 
@@ -1030,16 +1030,29 @@
 ());%0A%09%09%09
+%0A%09%09%09try%7B%0A%09%09%09%09
 coll.ins
@@ -1156,16 +1156,54 @@
 hed%22));%0A
+%09%09%09%7D%0A%09%09%09catch(MongoException e)%7B%0A%09%09%09%7D%0A
 %09%09%7D%0A%0A%09%09i
@@ -1643,16 +1643,15 @@
 ak;%0A
+
 %09%09%09%09%09%7D%0A
-%0A
 %09%09%09%09

Create unique key