package org.sagebionetworks.discussion.workers;

import java.util.Arrays;

import org.sagebionetworks.asynchronous.workers.changes.ChangeMessageDrivenRunner;
import org.sagebionetworks.common.util.progress.ProgressCallback;
import org.sagebionetworks.repo.model.dao.discussion.DiscussionReplyDAO;
import org.sagebionetworks.repo.model.dao.discussion.DiscussionThreadDAO;
import org.sagebionetworks.repo.model.discussion.DiscussionThreadReplyStat;
import org.sagebionetworks.repo.model.discussion.DiscussionThreadStat;
import org.sagebionetworks.repo.model.message.ChangeMessage;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.sagebionetworks.workers.util.aws.message.RecoverableMessageException;
import org.springframework.beans.factory.annotation.Autowired;

public class DiscussionThreadStatsWorker implements ChangeMessageDrivenRunner{
	@Autowired
	private DiscussionThreadDAO threadDao;
	@Autowired
	private DiscussionReplyDAO replyDao;

	@Override
	public void run(ProgressCallback<Void> progressCallback, ChangeMessage message)
			throws RecoverableMessageException {
		if (message.getChangeType() != ChangeType.UPDATE) {
			// only process update events
			return;
		}
		long threadId = Long.parseLong(message.getObjectId());

		DiscussionThreadStat stat = new DiscussionThreadStat();
		stat.setThreadId(threadId);
		stat.setActiveAuthors(replyDao.getActiveAuthors(threadId));
		progressCallback.progressMade(null);

		DiscussionThreadReplyStat replyStat = replyDao.getThreadReplyStat(threadId);
		stat.setLastActivity(replyStat.getLastActivity());
		stat.setNumberOfReplies(replyStat.getNumberOfReplies());
		progressCallback.progressMade(null);

		stat.setNumberOfViews(threadDao.countThreadView(threadId));
		progressCallback.progressMade(null);

		threadDao.updateThreadStats(Arrays.asList(stat));
	}

}

@@ -773,16 +773,80 @@
 towired;
+%0Aimport org.springframework.dao.DataIntegrityViolationException;
 %0A%0Apublic
@@ -1836,16 +1836,25 @@
 null);%0A%0A
+%09%09try %7B%0A%09
 %09%09thread
@@ -1897,14 +1897,111 @@
 stat));%0A
+%09%09%7D catch (DataIntegrityViolationException e) %7B%0A%09%09%09// the thread no longer exist, do nothing%0A%09%09%7D%0A
 %09%7D%0A%0A%7D%0A

deal with old message