package so.tio.inlearn.server.session;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import so.tio.inlearn.common.testing.TaskItem;
import so.tio.inlearn.common.testing.TestVariant;
public class TestAnswersHandler {
private TestVariant test;
private Map<Long, Map<String, List<String>>> allAnswers = new HashMap<Long, Map<String, List<String>>>();
private int userMark = 0;
private int maximumMark = 0;
private int allTasks = 0;
private int validTasks = 0;
public TestAnswersHandler(TestVariant test) {
this.test = test;
}
public void putAnswers(long taskId, Map<String, List<String>> answers) {
allAnswers.put(taskId, answers);
}
public boolean isTaskValid(long taskId){
Map<String, List<String>> answers = allAnswers.get(taskId);
TaskItem validTask = findTask(test, taskId);
if (validTask == null) {
System.err.println("task #" + taskId + " not found!");
return false;
}
int answersCount = 0;
// Counting answers
for(Entry<String, List<String>> a : answers.entrySet()){
answersCount += a.getValue().size();
}
List<HashMap<String, String>> validAnswers = validTask.getAnswers();
// Counting valid answers and check answers
int validAnswersCount = 0;
for (HashMap<String, String> validPairs : validAnswers) {
boolean isBad = false;
for(Entry<String, String> entry: validPairs.entrySet()){
validAnswersCount++;
if (answers.containsKey(entry.getKey()) && answers.get(entry.getKey()).contains(entry.getValue())) {
}
else{
isBad = true;
break;
}
}
if(!isBad && (answersCount <= validAnswersCount)){
return true;
}
}
return false;
}
public void checkTest(){
int mark = 0;
int validTasks = 0;
for(Entry<Long, Map<String, List<String>>> task: allAnswers.entrySet()){
long taskId = task.getKey();
if(isTaskValid(taskId)){
mark += getTaskCost(taskId);
validTasks++;
}
}
userMark = mark;
allTasks = test.getTasks().size();
maximumMark = test.getMaximumMark();
this.validTasks = validTasks;
}
private int getTaskCost(long taskId){
TaskItem task = findTask(test, taskId);
if(task == null){
return 0;
}
return task.getCost();
}
private TaskItem findTask(TestVariant test, long taskId){
TaskItem task = null;
// Finding task in current test
for (TaskItem currentItem : test.getTasks()) {
if (currentItem.getTaskId() == taskId) {
task = currentItem;
}
}
return task;
}
public int getUserMark() {
return userMark;
}
public int getAllTasks() {
return allTasks;
}
public int getValidTasks() {
return validTasks;
}
public int getMaximumMark() {
return maximumMark;
}
public String getTestName(){
return test.getName();
}
}