package com.uas.report.axis;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

@XmlRootElement(name = "errors")
public class ValidationErrors implements Serializable {

	private static final long serialVersionUID = 1L;

	private final List<ValidationError> errors;

	public ValidationErrors() {
		errors = new ArrayList<>();
	}

	public ValidationErrors(List<ValidationError> errors) {
		this.errors = errors;
	}

	public boolean isError() {
		return !errors.isEmpty();
	}

	@XmlElement(name = "error", type = ValidationError.class)
	public List<ValidationError> getErrors() {
		return errors;
	}

	public void add(ValidationError error) {
		errors.add(error);
	}

	public String toString() {
		if (!isError()) {
			return "No errors";
		}

		StringBuffer sb = new StringBuffer();
		sb.append(errors.size());
		sb.append(" error(s)\n");
		for (Iterator<ValidationError> it = errors.iterator(); it.hasNext();) {
			ValidationError error = it.next();
			sb.append(error.toString());
			sb.append('\n');
		}
		return sb.toString();
	}

	public void removeError(String code, String field) {
		for (Iterator<ValidationError> it = errors.iterator(); it.hasNext();) {
			ValidationError error = it.next();
			if (matches(error, code, field)) {
				it.remove();
			}
		}
	}

	protected boolean matches(ValidationError error, String code, String field) {
		return code.equals(error.getErrorCode()) && field.equals(error.getField());
	}

}
