/*******************************************************************************

* Copyright (c) 2006 IONA Technologies PLC

* All rights reserved. This program and the accompanying materials

* are made available under the terms of the Eclipse Public License v1.0

* which accompanies this distribution, and is available at

* http://www.eclipse.org/legal/epl-v10.html

* 

* Contributors:

*     IONA Technologies PLC - initial API and implementation

*******************************************************************************/
package org.eclipse.stp.sc.common.validator;

import java.util.ArrayList;

import org.eclipse.stp.common.logging.LoggingProxy;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class MultiErrorHandler implements ErrorHandler {
	
	private static final LoggingProxy LOG = LoggingProxy.getlogger(MultiErrorHandler.class);
	
	private static final String ERROR_MSG_PREFIX = "The value";
	private ArrayList<SAXParseException> errorList = new ArrayList<SAXParseException>();
	private int errorCount = 0;
	
	
	StringBuffer errorMsg = new StringBuffer();
	public void error(SAXParseException exception) throws SAXException {
		addError(exception);
	}

	public void fatalError(SAXParseException exception) throws SAXException {
		addError(exception);

	}

	public void warning(SAXParseException exception) throws SAXException {
		//dothing for the warning
	}
	
	public ArrayList<SAXParseException> getAllErrors() {
		return errorList;
	}
	
	private void addError(SAXParseException ex) {
		LOG.debug("parser add error:" + ex);
		errorCount ++;
		errorList.add(ex);
		//we do not put line number and column number in the msg for now
		//ex.getLineNumber()
		//ex.getColumnNumber()
		errorMsg.append(parseErrorMsg(ex.getMessage()));
		
	}
	
	private String parseErrorMsg(String msg) {
		/**
		 * we only deal with type value set validation msg for now
		 */
		if (msg.indexOf(ERROR_MSG_PREFIX) > 0 && msg.indexOf("is not valid")>0) {
			return msg.substring(msg.indexOf(ERROR_MSG_PREFIX));
		}
		return "";
	}
	
	public int getErrorCount() {
		return errorCount;
	}
	
	public String getErrorMsg() {
		return errorMsg.toString();
	}
	
	public void reset() {
		errorCount = 0;
		errorMsg = new StringBuffer();
		errorList.clear();
	}

}
