/*
 * Copyright 2006 Mask@ Project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.maskat.xml.xmlbeans;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions;
import org.apache.xmlbeans.impl.inst2xsd.XsdGenStrategy;
import org.apache.xmlbeans.impl.inst2xsd.util.TypeSystemHolder;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
import org.w3c.dom.Node;

public class InstToXsd {
	/**
	 * XMLインスタンスからスキーマを生成する 生成されるスキーマはOutputStreamで返す
	 * 
	 * @param stream
	 * @param node
	 *            XMLインスタンスのノード
	 * @throws IOException
	 * @throws XmlException
	 */
	public static void transfer(OutputStream stream, Node node) throws IOException,
			XmlException {
		Inst2XsdOptions inst2XsdOptions = new Inst2XsdOptions();

		inst2XsdOptions.setDesign(Inst2XsdOptions.DESIGN_SALAMI_SLICE);
		inst2XsdOptions.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART);
		inst2XsdOptions.setUseEnumerations(1);// never enumerate
		inst2XsdOptions.setVerbose(false);

		XmlObject xmlInstances = XmlObject.Factory.parse(node);

		// create structure
		TypeSystemHolder typeSystemHolder = new TypeSystemHolder();
		XsdGenStrategy strategy = new EventDefStrategy();
		strategy.processDoc(new XmlObject[] { xmlInstances }, inst2XsdOptions,
				typeSystemHolder);
		SchemaDocument[] schemaDocs = typeSystemHolder.getSchemaDocuments();

		for (int i = 0; i < schemaDocs.length; i++) {
			SchemaDocument schema = schemaDocs[i];

			XmlOptions options = new XmlOptions().setSavePrettyPrint()
					.setCharacterEncoding("UTF-8");
			schema.save(stream, options);
		}

	}
}
