/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * 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:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.core.betwixt;

import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.betwixt.XMLIntrospector;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.io.IOUtils;
import org.xml.sax.InputSource;

import org.maskat.core.event.EventElement;
import org.maskat.core.event.Param;
import org.maskat.core.event.Result;

public class MessageSchemaGenerator {

	public static final String MESSAGE_XSD_CONFIG = "xsdConfig.betwixt";

	public static InputStream generateRequestXMLSchema(Param param) throws Exception {
		return generateMessageXMLSchema(param);
	}

	public static InputStream generateResponseXMLSchema(Result result) throws Exception {
		return generateMessageXMLSchema(result);
	}

	private static InputStream generateMessageXMLSchema(EventElement element)
			throws Exception {
		StringWriter outputWriter = new StringWriter();
		outputWriter.write("<?xml version='1.0' encoding='UTF-8' ?>\n");

		BeanWriter beanWriter = new BeanWriter(outputWriter);
		beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(
				false);
		beanWriter.getBindingConfiguration().setMapIDs(false);
		beanWriter.getBindingConfiguration().setValueSuppressionStrategy(
				new MessageSchemaValueSuppressionStrategy());
		beanWriter.enablePrettyPrint();
		beanWriter.setInitialIndentLevel(0);
		beanWriter.setWriteEmptyElements(false);

		XMLIntrospector intro = beanWriter.getXMLIntrospector();
		InputStream in = MaskatBeanIO.class.getResourceAsStream(MESSAGE_XSD_CONFIG);
		intro.register(new InputSource(in));

		beanWriter.write(element);
		return IOUtils.toInputStream(outputWriter.toString());
	}

}
