package de.uka.ipd.consensus.impl;

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

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.tm4j.topicmap.TopicMapProcessingException;
import org.tm4j.topicmap.utils.TopicMapWalker;
import org.tm4j.topicmap.utils.WalkerFilter;
import org.tm4j.topicmap.utils.XTMWriter;

import de.uka.ipd.consensus.foundation.logging.LoggingManager;
import de.uka.ipd.consensus.foundation.ontology.ExportHandler;
import de.uka.ipd.consensus.foundation.ontology.OntologyManager;
import de.uka.ipd.consensus.foundation.ontology.OntologyManagerException;

/**
 * 
 * TODO
 * @author Thomas Much
 * @version 2006-06-14
 */
public class XTMExportHandler implements ExportHandler {
	
	private OntologyManagerImpl omi;
	private LoggingManager      logging;


	public XTMExportHandler(LoggingManager lm, OntologyManager om) {
		// alternativ Konstruktor mit Properties als zusätzlichem 1. Parameter, oder nur mit OntologyManager, oder ganz ohne Parameter
		this.logging = lm;
		this.omi     = (OntologyManagerImpl)om;
	}


	public void exportOntology(OutputStream out, boolean exportInternals) throws IOException,OntologyManagerException {

		TopicMapWalker tmw = new TopicMapWalker();

		tmw.setWalkTypeInstanceAssociations(true);
		
		XTMWriter writer = new XTMWriter();

		if (exportInternals) {
			tmw.setHandler( writer );
		}
		else {
			WalkerFilter filter = new XTMExportInternalFilter( omi );

			filter.setHandler( writer );

			tmw.setHandler( filter );
		}

		OutputFormat of = new OutputFormat();

		of.setEncoding("UTF-8");
		of.setIndenting(true);
		of.setIndent(2);

		XMLSerializer serializer = new XMLSerializer(out,of);

		writer.setContentHandler(serializer);

		try {
			logging.debug("Exporting TopicMap " + omi.getTopicMap() + (exportInternals ? " (incl. internal types)" : ""));
			tmw.walk( omi.getTopicMap() );
		}
		catch (TopicMapProcessingException e) {
			throw new OntologyManagerException(e);
		}
	}

	
	public String getContentType() {
		return "text/xml";
	}

	
	public String getExtension() {
		return "xtm";
	}


	public String getDescription() {
		return "";
	}

}
