/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.correctness.builder.attributes;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class ContestCorrectionBuilder {

	private String contestId;

	private Map<String, Integer> questions = new HashMap<>();

	private final AttributesCorrectnessBuilder attributesCorrectnessBuilder;

	public ContestCorrectionBuilder(String contestId, AttributesCorrectnessBuilder attributesCorrectnessBuilder) {
		this.contestId = contestId;
		this.attributesCorrectnessBuilder = attributesCorrectnessBuilder;
	}

	public ContestCorrectionBuilder addQuestion(String attributeId, int max) {
		questions.put(attributeId, max);
		return this;
	}

	public AttributesCorrectnessBuilder build() {
		return attributesCorrectnessBuilder;
	}

	public void generateCorrectnessCode(StringBuilder sb) {
		Set<Entry<String, Integer>> entrySet = questions.entrySet();
		for (Entry<String, Integer> entry : entrySet) {
			sb.append("result = function (subSelection, callbackFunction) {");
			sb.append("var partialResult = true;");
			sb.append("var selectionName = '").append(contestId).append("';");
			sb.append("var attributeName = '").append(entry.getKey()).append("';");
			sb.append("var max = ").append(entry.getValue().intValue()).append(";");
			sb.append("var count = 0;");
			sb.append("for (i = 0; i < subSelection.length; i++) {");
			sb.append("var submittedOption = subSelection[i];");
			sb.append("if (submittedOption.indexOf(attributeName) > -1) {");
			sb.append("count++;");
			sb.append("}");
			sb.append("}");
			sb.append("if (count < max) {");
			sb.append("callbackFunction('MIN_ERROR', selectionName);");
			sb.append("partialResult = false;");
			sb.append("}");
			sb.append("if (count > max) {");
			sb.append("callbackFunction('MAX_ERROR', selectionName);");
			sb.append("partialResult = false;");
			sb.append("}");
			sb.append("return partialResult;");
			sb.append("}");
			sb.append("(selection, callbackFunction) && result;");
		}
	}
}
