package cz.zajezdy.data.bengine.configuration.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import cz.zajezdy.data.bengine.configuration.Configuration;
import cz.zajezdy.data.bengine.configuration.Document;
import cz.zajezdy.data.bengine.configuration.InputValidation;
import cz.zajezdy.data.bengine.configuration.Rule;


public class BasicConfiguration<TDoc extends Document> implements Configuration<TDoc> {

	private String version;
	private TDoc document;
	private CopyOnWriteArrayList<BasicInputValidation> inputValidation;
	private CopyOnWriteArrayList<BasicRule> rules;
	private CopyOnWriteArrayList<String> postExecution;
	private CopyOnWriteArrayList<String> preExecution;
	private boolean rulesSorted = false;

	private String __jsonDocument;

	public String getVersion() {
		return version;
	}

	public List<? extends InputValidation> getInputValidations() {
		return inputValidation;
	}

	public TDoc getDocument() {
		return document;
	}

	@Override
	public synchronized List<? extends Rule> getRules() {
		// sort the rules synchronized on first access
		// ensures reusage in multithreading and correct behavior
		if (!rulesSorted) {
			sortRules(rules);
		}
		return rules;
	}

	private void sortRules(List<? extends Rule> rules) {
		Collections.sort(rules, new Comparator<Rule>() {

			public int compare(Rule r1, Rule r2) {
				return r1.getPriority() < r2.getPriority() ? -1 : 1;
			}
		});
	}

	@Override
	public List<String> getPostExecution() {
		return postExecution;
	}

	@Override
	public List<String> getPreExecution() {
		return preExecution;
	}

	@Override
	public String getJsonDocument() {
		return __jsonDocument;
	}

	@Override
	public void setJsonDocument(String jsonDocument) {
		__jsonDocument = jsonDocument;
	}
}

@@ -1058,29 +1058,154 @@
 %09public 
-synchronized 
+List%3C? extends Rule%3E getRules() %7B%0A%09%09if (!rulesSorted) %7B%0A%09%09%09sortRules(rules);%0A%09%09%7D%0A%09%09return rules;%0A%09%7D%0A%0A%09private synchronized void sortRules(
 List%3C? e
@@ -1213,33 +1213,29 @@
 tends Rule%3E 
-getR
+r
 ules
-(
 ) %7B%0A%09%09// sor
@@ -1364,265 +1364,87 @@
 %0A%09%09%09
-sortRules(rules);%0A%09%09%7D%0A%09%09return rules;%0A%09%7D%0A%0A%09private void sortRules(List%3C? extends Rule%3E rules) %7B%0A%09%09Collections.sort(rules, new Comparator%3CRule%3E() %7B%0A%0A%09%09%09public int 
+rules.sort(Comparator.
 compar
-e
+ing
 (Rule
- r1, Rule r2) %7B%0A%09%09%09%09return r1.getPriority() %3C r2.getPriority() ? -1 : 1;%0A%09%09%09%7D%0A%09%09%7D);
+::getPriority));%0A%09%09%09rulesSorted = true;%0A%09%09%7D
 %0A%09%7D%0A

improve performance: rulesStored was never set to true + reduce lock size