package cz.brmlab.brmson.blanqa.phase.answer;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.oaqa.model.Answer;

import cz.brmlab.brmson.takepig.basephase.AbstractAnswerGenerator;


/**
 * Answer type generator that will simply sort the candidates by their score
 * in descending order.
 *
 * Example (for question "What prize did Watson receive?"):
 *   - inherit: jdbc.sqlite.cse.phase
 *     name: answer-generator
 *     options: |
 *       - inherit: phases.answer.basic
 */

public class AnswerGenerator extends AbstractAnswerGenerator {
	@Override
	public List<Answer> generateFinalAnswers(
			String answerType, List<String> keyterms,
			List<Answer> answerCandidates) {

		// deduplicate candidates
		Map<String, Answer> results = new LinkedHashMap<String, Answer>();
		for (Answer candidate : answerCandidates) {
			String text = candidate.getText();
			Answer result = results.get(text);
			if (result == null) {
				// first time seen
				results.put(text, candidate);
			} else {
				// merge questions
				// TODO merge searchresults
				// Increase score
				result.setScore(result.getScore() + candidate.getScore());
			}
		}

		// sort answer candidates by sum of scores
		// (use original order for tie-breaking)
		Answer[] sorted = results.values().toArray(new Answer[results.size()]);
		Arrays.sort(sorted, new Comparator<Answer>(){ @Override
			public int compare(Answer a1, Answer a2){
				return - (int) (a1.getScore() - a2.getScore());
			} } );
		List<Answer> finalAnswers = new ArrayList<Answer>(sorted.length);
		for (Answer result : sorted) {
			finalAnswers.add(result);
		}

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < Math.min(5, finalAnswers.size()); i++) {
			sb.append((i > 0 ? ", " : ""));
			sb.append("\"" + finalAnswers.get(i) + "\"");
			sb.append("\"" + finalAnswers.get(i).getScore() + "\"");
		}
		log("Final top answers: " + (sb.length() > 0 ? sb : "No answers found."));
		
		return finalAnswers;
	}
}

@@ -1296,21 +1296,39 @@
  by 
-sum of scores
+their scores in ascending order
 %0A%09%09/
@@ -1559,19 +1559,25 @@
 urn 
-- (int) (a1
+Double.valueOf(a2
 .get
@@ -1587,13 +1587,37 @@
 re()
- - a2
+).compareTo(Double.valueOf(a1
 .get
@@ -1620,24 +1620,25 @@
 .getScore())
+)
 ;%0A%09%09%09%7D %7D );%0A
@@ -1951,16 +1951,26 @@
 s.get(i)
+.getText()
  + %22%5C%22%22)
@@ -1977,34 +1977,33 @@
 ;%0A%09%09%09sb.append(%22
-%5C%22
+:
 %22 + finalAnswers
@@ -2020,23 +2020,16 @@
 tScore()
- + %22%5C%22%22
 );%0A%09%09%7D%0A%09

Fix the answer sorting; improve the debug print