package de.uka.ipd.consensus.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;

import org.tm4j.topicmap.ProviderTransaction;
import org.tm4j.topicmap.TopicMap;
import org.tm4j.topicmap.TopicMapProviderException;
import org.tm4j.topicmap.source.SerializedTopicMapSource;
import org.tm4j.topicmap.source.TopicMapSource;

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

/**
 * 
 * TODO
 * has to keep base locator!
 * first remove old ontology, then import new one
 * called only on startup
 * @author Thomas Much
 * @version 2006-06-14
 */
public class XTMImportHandler implements ImportHandler {

	private OntologyManagerImpl omi;
	private LoggingManager      logging;


	public XTMImportHandler(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 importOntology(InputStream in) throws IOException,OntologyManagerException {
		try {
			TopicMap old = omi.getTopicMap();

			if (old != null) {
				logging.debug("Removing TopicMap: " + old );
				omi.setTopicMap( null );
				omi.getTopicMapProvider().removeTopicMap( old );
			}

			TopicMapSource tmsrc = new SerializedTopicMapSource( in, omi.getTopicMapBase() );
		
			TopicMap tm = omi.getTopicMapProvider().addTopicMap( tmsrc );

			logging.debug("TopicMap loaded: " + tm );
			
			omi.setTopicMap( tm );
			omi.createTopicTypes();
		}
		catch (TopicMapProviderException e) {
			throw new OntologyManagerException(e);
		}
		finally {
			if (in != null) {
				in.close();
			}			
		}
	}


	public void mergeOntology(InputStream in, Collection errors) throws IOException {
		try {
			// ugly hack for bug in TM4J that does not recognise open TAs in XTMBuilder
			// (OntologyManager's TA methods ensure that a TA isn't closed twice)
			ProviderTransaction ta = omi.getTopicMapProvider().getOpenTransaction();
			if (ta != null) {
				ta.commit();
			}

			TopicMap tm = omi.getTopicMap();
			
			TopicMapSource tmsrc = new SerializedTopicMapSource( in, omi.getTopicMapBase() );
			
			omi.getTopicMapProvider().addTopicMap( tmsrc, tm );
			
			logging.debug("TopicMap merged: " + tm );
		}
		catch (Exception e) {
			if (errors != null) {
				errors.add( e );
			}
		}
		finally {
			if (in != null) {
				in.close();
			}			
		}
	}


	public boolean canMerge() {
		return true;
	}

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

	
	public String getDescription() {
		return "";
	}

}
