import java.lang.Exception
import com.sun.xml.xsom.XSSchemaSet 
import com.sun.xml.xsom.parser.XSOMParser 
import com.sun.xml.xsom.util.DomAnnotationParserFactory 

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

XSSchemaSet parse(String schemaSource) throws Exception {
	XSOMParser parser = new XSOMParser();
	parser.setAnnotationParser(new DomAnnotationParserFactory());
	
	File schemaSourceFile = new File(schemaSource);		
	
	def entityResolver = {String publicId, systemId -> 
		def fileProtocolMatch = (systemId =~ /^file:.+/);
		if (!fileProtocolMatch || !new File(fileProtocolMatch[0]).exists()) {
			String schemaFileName = (systemId =~ /\/[^\/]+$/)[0];
			
			File entityLocation = new File(schemaSourceFile.getParentFile(), schemaFileName);
			return new InputSource(entityLocation.toURI().toString());
		}
		
		return new InputSource(systemId);
	} as EntityResolver;
	
	parser.setEntityResolver(entityResolver);
	parser.parse(schemaSourceFile);
	
	return parser.getResult();
}

try {
	def targetNamespaceParam = project.properties['targetNamespace'];

	def sourceSchemaParam = project.properties['sourceSchema'];
	String sourceSchemaFileName = project.basedir.getAbsolutePath() + '/' + sourceSchemaParam;
	
	def outputFileParam = project.properties['outputFile'];
	String outputFileName = project.build.directory + '/' + outputFileParam;
	
	log.info("Parsing: " + sourceSchemaFileName);
	log.info("Writing attributes XML data to: " + outputFileName);
	
	File outputFile = new File(outputFileName);

	if (outputFile.exists()) {
		File inputFile = new File(sourceSchemaFileName);
		if(outputFile.lastModified() > inputFile.lastModified()){
			return;
		} 
		outputFile.delete();
	} else {
		outputFile.getParentFile().mkdirs();
	}
	
	outputFile.createNewFile();
	
	XSSchemaSet schemaSet = parse(sourceSchemaFileName);
	
	if (schemaSet == null) {
	    fail("Unknown error parsing schema file");
	}
	
	SchemaProcessor schemaProcessor = new SchemaProcessor(schemaSet, targetNamespaceParam);
	schemaProcessor.buildModel();
	schemaProcessor.serializeModel(new FileOutputStream(outputFileName));

} catch (Exception e) {
	fail(e);
}
