/**
 *
 */
package fr.emse.gitlab.saref.entities.tests;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import fr.emse.gitlab.saref.entities.git.MasterVersion;
import fr.emse.gitlab.saref.entities.git.ReleaseVersion;
import fr.emse.gitlab.saref.entities.git.Version;

/**
 * @author Omar Qawasmeh
 *
 *
 */
@XmlRootElement(name = "testsuites")
@XmlType(propOrder = { "name", "tests", "failures", "errors", "testSuitesList" })
public class TestSuites implements Serializable {

	@XmlAttribute
	String name = "";

	@XmlAttribute
	int tests = 0;

	@XmlAttribute
	int failures = 0;
	
	@XmlAttribute
	int errors = 0;
	
	@XmlElement(name="testsuite")
	private List<TestSuite> testSuitesList = new ArrayList<>();

	private transient Map<String, TestSuite> testSuitesMap;
	
	public TestSuites() {}
	
	public TestSuites(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}

	public int getFailures() {
		return failures;
	}

	public int getErrors() {
		return errors;
	}

	public TestSuite get(String name) {
		if(testSuitesMap == null) {
			testSuitesMap = new HashMap<>();
			for(TestSuite testSuite : testSuitesList) {
				testSuitesMap.put(testSuite.getName(), testSuite);
			}
		}
		TestSuite testSuite = testSuitesMap.get(name);
		if(testSuite == null) {
			testSuite = new TestSuite(this, name);
			testSuitesMap.put(name, testSuite);
			testSuitesList.add(testSuite);
		}
		return testSuite;
	}

	public void clean() {
		testSuitesList.removeIf((ts) -> {
			return ts.getErrors() + ts.getFailures() == 0;
		});		
		testSuitesMap.values().removeIf((ts) -> {
			return ts.getErrors() + ts.getFailures() == 0;
		});
		
		testSuitesList.forEach((ts)->{
			// put errors first
			Collections.sort(ts.getTestCases(), new Comparator<TestCase>() {
				@Override
				public int compare(TestCase o1, TestCase o2) {
					if (o1.getStatus().equals(o2.getStatus())) {
						return 0;
					}
					if (o1.getStatus().equals(TestCase.Status.ERROR.getName())) {
						return -1;
					}
					if (o2.getStatus().equals(TestCase.Status.ERROR.getName())) {
						return 1;
					}
					return 0;
				}
			});
			
		});
	}

}