/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
 */
package fr.gouv.culture.sdx.application;

import java.util.Enumeration;

import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.AggregatedValidity;

import fr.gouv.culture.sdx.documentbase.DocumentBase;
import fr.gouv.culture.sdx.exception.SDXException;

public class ApplicationSourceValidity implements SourceValidity {

	/** An aggregated source validity object for keeping track of all document bases */
	private AggregatedValidity agg;
	
	public ApplicationSourceValidity(Application app) {
		
		// We create an aggregated object
		this.agg = new AggregatedValidity();
		
		// We add all document base validity objects except the user document base
		Enumeration ids = app.getDocumentBasesIds();
		while ( ids.hasMoreElements() ) {
			try {
				DocumentBase db = app.getDocumentBase((String)ids.nextElement());
				if ( !db.getId().equals(Application.USER_DOCUMENT_BASE_ID) ) {
					agg.add(db.getSourceValidity());
				}
			}
			catch (SDXException e ) {
				// Do nothing, don't add it
			}
		}
	}

	public int isValid() {
		// use the internal aggregated validity object
		return agg.isValid();
	}

	public int isValid(SourceValidity sv) {
		// use the internal aggregated validity object
		if ( sv instanceof ApplicationSourceValidity ) {
			return agg.isValid(((ApplicationSourceValidity)sv).getAggregatedValidity());
		}
		else return -1;
	}
	
	public AggregatedValidity getAggregatedValidity() {
		return this.agg;
	}

}
