package reciter.database.mongo.repository.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.BasicDBObject;
import com.mongodb.WriteResult;

import reciter.database.mongo.model.ESearchPmid;
import reciter.database.mongo.model.ESearchResult;
import reciter.database.mongo.repository.ESearchResultRepositoryCustom;

public class ESearchResultRepositoryImpl implements ESearchResultRepositoryCustom {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public boolean pushESearchResult(ESearchResult eSearchResult) {
		return false;
		//		String cwid = eSearchResult.getCwid();
		//		ESearchPmid eSearchPmid = eSearchResult.getEsearchResult();
		//		// Insert each ESearchPmid object into the collection.
		//		BasicDBObject basicDbObject = new BasicDBObject("$addToSet", new BasicDBObject("eSearchPmid", new BasicDBObject("$each", eSearchPmid)));
		//		WriteResult writeResult = mongoTemplate.getCollection("esearchresult").update(new BasicDBObject("cwid", cwid), basicDbObject, true, false);
		//		return writeResult.wasAcknowledged();
	}

	@Override
	public WriteResult update(String cwid, ESearchPmid eSearchPmid) {
		
		BasicDBObject query = new BasicDBObject("cwid", cwid).append("eSearchPmid.retrievalStrategyName", eSearchPmid.getRetrievalStrategyName());
		BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("eSearchPmid.pmids", eSearchPmid.getPmids()));
		
		WriteResult writeResult = mongoTemplate.getCollection("esearchresult").update(query, update, true, false);
		return writeResult;
	}
	
	@Override
	public boolean existByCwidAndRetrievalStrategyName(String cwid, String retrievalStrategyName) {
		BasicDBObject query = new BasicDBObject("cwid", cwid).append("eSearchPmid.retrievalStrategyName", retrievalStrategyName);
		return mongoTemplate.getCollection("esearchresult").findOne(query) != null;
	}
}

@@ -40,24 +40,162 @@
 ry.impl;%0D%0A%0D%0A
+import java.time.Instant;%0D%0Aimport java.time.LocalDate;%0D%0Aimport java.time.ZoneId;%0D%0Aimport java.time.ZoneOffset;%0D%0Aimport java.util.Date;%0D%0A%0D%0A
 import org.s
@@ -1393,16 +1393,218 @@
  %7B%0D%0A%09%09%0D%0A
+%09%09// use java.util.Date until MongoDB driver supports LocalDateTime codec%0D%0A%09%09Instant instant = eSearchPmid.getRetrievalDate().atZone(ZoneOffset.UTC).toInstant();%0D%0A%09%09Date date = Date.from(instant);%0D%0A%09%09%0D%0A
 %09%09BasicD
@@ -1784,24 +1784,30 @@
 ect(%22$set%22, 
+%0D%0A%09%09%09%09
 new BasicDBO
@@ -1856,16 +1856,64 @@
 Pmids())
+%0D%0A%09%09%09%09.append(%22eSearchPmid.retrievalDate%22, date)
 );%0D%0A%09%09%0D%0A

Update 'retrievalDate' in ESearchResult.