/*
 * 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.feedback;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.scytl.products.ov.commons.correctness.builder.CorrectnessBuilder;
import com.scytl.products.ov.commons.correctness.builder.CorrectnessUtil;

public class CorrectnessFeedback {

	@JsonProperty(value = "result")
	private Boolean result;

	@JsonIgnore
	private List<ReportedError> errors;
	
	public static String decorateRule(CorrectnessBuilder correctness, boolean safeEncoded) {
		StringBuilder sb = new StringBuilder();
		sb.append("function " + CorrectnessUtil.EVALUATE_CORRECTNESS_WITH_FEEDBACK + "(selection){");
		sb.append("var result = {};");
		sb.append("var errors = [];");
		sb.append("var callbackForErrors = function (type, reference) {");
		sb.append("var errorHappened = {};");
		sb.append("errorHappened['type'] = type;");
		sb.append("errorHappened['reference'] = reference;");
		sb.append("errors.push(errorHappened);");
		sb.append("};");
		sb.append("var booleanResult = evaluateCorrectness(selection, callbackForErrors);");
		sb.append("result['result'] = booleanResult;");
		sb.append("result['errors'] = errors;");
		sb.append("return JSON.stringify(result);");
		sb.append("};");
		sb.append(safeEncoded ? correctness.buildWithSafeEncoding() : correctness.build());
		return sb.toString();
	}	
	
	public static String decorateRule(String correctness) {
		if( correctness == null) {
			throw new NullPointerException("Correctness rule to be decorated cannot be null.");
		}
		StringBuilder sb = new StringBuilder();
		sb.append("function " + CorrectnessUtil.EVALUATE_CORRECTNESS_WITH_FEEDBACK + "(selection){");
		sb.append("var result = {};");
		sb.append("var errors = [];");
		sb.append("var callbackForErrors = function (type, reference) {");
		sb.append("var errorHappened = {};");
		sb.append("errorHappened['type'] = type;");
		sb.append("errorHappened['reference'] = reference;");
		sb.append("errors.push(errorHappened);");
		sb.append("};");
		sb.append("var booleanResult = evaluateCorrectness(selection, callbackForErrors);");
		sb.append("result['result'] = booleanResult;");
		sb.append("result['errors'] = errors;");
		sb.append("return JSON.stringify(result);");
		sb.append("};");
		sb.append(correctness);
		return sb.toString();
	}

	public Boolean getResult() {
		return result;
	}

	public void setResult(Boolean result) {
		this.result = result;
	}

	public List<ReportedError> getErrors() {
		return errors;
	}

	public void setErrors(List<ReportedError> errors) {
		this.errors = errors;
	}

}
