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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.ScriptException;

import org.slf4j.Logger;

import com.scytl.products.ov.commons.correctness.feedback.CorrectnessFeedback;
import com.scytl.products.ov.commons.correctness.internal.AttributeCorrectnessEvaluator;

public class CachedAttributeCorrectnessEvaluator {

	private Map<String, AttributeCorrectnessEvaluator> evaluators = new HashMap<>();
	private Logger logger;

	public CachedAttributeCorrectnessEvaluator(Logger logger) {
		this.logger = logger;
	}

	public CorrectnessFeedback evaluateCorrectness(String correctnessRule, List<List<String>> optionAttributes) {
		CorrectnessFeedback correctnessResult;
		synchronized (evaluators) {
			try {
				if (!evaluators.containsKey(correctnessRule)) {
					evaluators.put(correctnessRule, new AttributeCorrectnessEvaluator(logger, correctnessRule));
				}
				correctnessResult = evaluators.get(correctnessRule).checkCorrectness(optionAttributes);
			} catch (ScriptException e) {
				throw new IllegalArgumentException(e);
			}
		}
		return correctnessResult;
	}

}
