/*
 * MiningMart Version 1.0
 * 
 * Copyright (C) 2006 Martin Scholz, Timm Euler, 
 *                    Daniel Hakenjos, Katharina Morik
 *
 * Contact: miningmart@ls8.cs.uni-dortmund.de
 *
 * A list of contributing developers (other than the copyright 
 * holders) can be found at
 * http://mmart.cs.uni-dortmund.de/downloads/download.html
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program, see the file MM_HOME/LICENSE; if not, write
 * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA 02110-1301, USA.
 */
package edu.udo.cs.miningmart.compiler.wrapper.dista.Sequence;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.sql.ResultSet;

import edu.udo.cs.miningmart.operator.ConceptOperator;
import edu.udo.cs.miningmart.operator.ExecutableOperator;
import edu.udo.cs.miningmart.operator.FeatureConstruction;
import edu.udo.cs.miningmart.compiler.utils.DrawSample;
import edu.udo.cs.miningmart.compiler.wrapper.dista.ColumnInfo;
import edu.udo.cs.miningmart.compiler.wrapper.dista.DMException;
import edu.udo.cs.miningmart.compiler.wrapper.dista.Wrapper;

import edu.udo.cs.miningmart.compiler.SystemPropertyInterface;
import edu.udo.cs.miningmart.db.DB;
import edu.udo.cs.miningmart.exception.DbConnectionClosed;
import edu.udo.cs.miningmart.exception.M4CompilerError;
import edu.udo.cs.miningmart.exception.M4Exception;
import edu.udo.cs.miningmart.m4.Columnset;
import edu.udo.cs.miningmart.m4.Concept;
import edu.udo.cs.miningmart.m4.Step;

/**
 * @author Alessandro Serra, Timm Euler
 * @version $Id: CorrelWrapper.java,v 1.4 2006/04/11 14:10:18 euler Exp $
 */
public class CorrelWrapper extends Wrapper {
	protected String m_file_name;
	protected PrintWriter m_data;
	CorrelResult m_correl_result;
	private String sampleTableName;

	public CorrelWrapper(Step step, ExecutableOperator exOp) throws Exception {
		super(step, exOp);
	}

	public void checkMetaData() throws Exception {
		if(m_md.getColumnToLearn()!=null) {
			throw new DMException("Sequence Correl"+
				" is an unsupervised learning"+
				"algoritm.  It don't require a column to learn");
		}
		if(m_md.getColumnInfos().size()!=1) {
			throw new DMException("Sequence Correl"+
				" require only one column");
		}
		ColumnInfo ci=(ColumnInfo)
			m_md.getColumnInfos().elementAt(0);
		if(ci.getConceptType()!=ColumnInfo.SCALAR && 
			ci.getDataType()!=ColumnInfo.STRING) {	
			throw new DMException("Sequence Correl "+
				" requite a column with a String "+
				"oracol type and with a scalar concept type");
		}
	}

	protected String makeQuery() throws DMException, DbConnectionClosed, M4CompilerError {
		// *** Determine name of the current Columnset: ***
		final Columnset cs;
		{ 
			Columnset tmp = null;
			Step theStep = this.getStep();
			if (theStep != null) {
				ExecutableOperator op = this.getExecutableOperator();			
				Concept inputCon = null;
				if (op != null && op instanceof FeatureConstruction) {
					inputCon = ((FeatureConstruction) op).getTheInputConcept();
				}
				else if (op != null && op instanceof ConceptOperator) {
					inputCon = ((ConceptOperator) op).getInputConcept();
				}
				
				if (inputCon != null) {
					try {
						tmp = (inputCon == null) ? null : (Columnset) inputCon.getCurrentColumnSet();
					}
   					catch (M4Exception m4e)
			   		{   throw new M4CompilerError("M4 interface error in CorrelWrapper: " + m4e.getMessage());  } 
				}
			}
			cs = tmp;			
			
			if (cs == null) {
			  	throw new DMException(
			  		"Could not determine Columnset in class miningmart.compiler.wrapper.dista.CorrelWrapper!"
			  	);
			}
		}

		// *** Sampling: ***
		final long stepId = this.getStep().getId();
		final String sampleTableName = "SAMPLE_" + stepId;
		this.setSampleTableName(sampleTableName);
		{
			String tempTableName = "TMP_" + stepId;
			try {
				new DrawSample(cs, null, sampleTableName, tempTableName, null, m_sample_size, null, this.getM4Db());
				this.getM4Db().addTableToTrash(this.getSampleTableName(), cs.getSchema(), stepId);
			}
			catch (M4CompilerError e) {
				throw new DMException(e.getMessage());
			}
		}

		// *** Construct the query based on the materialized sample: ***
		String query = "select ";
		ColumnInfo ci = (ColumnInfo) m_md.getColumnInfos().elementAt(0);
		query += ci.getName();
		query += " from " + this.getSampleTableName() + " ";
		if (m_md.getColumnToLearn() != null) {
			query += "where "
				   + m_md.getColumnToLearn().getName()
				   + " is not null ";
		}
		
		return query;
	}

	protected void exportTable() throws Exception {
		String temporaryDir = SystemPropertyInterface.getProperty(SystemPropertyInterface.NAME_MM_TEMP);
		m_file_name=temporaryDir + File.separator + "seq_"+
				m_md.getTableName();
		Writer w= new BufferedWriter(new FileWriter(m_file_name+".obj"));
		m_data=new PrintWriter(w);
		exportData();
		m_data.close();
		m_data=null;
	}

	protected void exportData() throws Exception {
		ResultSet res = null;
		try {
			res = this.getM4Db().executeBusinessSqlRead(makeQuery());
			// ResultSetMetaData res_md=res.getMetaData();
			int i=0;
			while(res.next()) {
				// ColumnInfo ci=(ColumnInfo) m_md.getColumnInfos().elementAt(0);
				m_data.print(i);
				m_data.print(" 1 0 ");
				m_data.print(res.getString(1));
				m_data.print("\n");
				++i;
			}
		}
		finally {
			DB.closeResultSet(res);
		}
	}

	protected void callTool() throws Exception {
		String temporaryDir = SystemPropertyInterface.getProperty(SystemPropertyInterface.NAME_MM_TEMP);
		callScript("cp " + m_ml_home + "/etc/correl_param.txt " + temporaryDir + File.separator + ".param");
		callScript("ftextract "+ m_file_name+".obj");
		callScript("seq_pattern2dlf "+ m_file_name+".obj.result "+
			m_file_name);
	}
	protected void clean() throws Exception {
		String temporaryDir = SystemPropertyInterface.getProperty(SystemPropertyInterface.NAME_MM_TEMP);
		if (temporaryDir == null || temporaryDir.trim().length() == 0)
			return;
			
		String s = File.separator;
		callScript("rm -f " + temporaryDir + s + ".list "+ 
				temporaryDir + s + ".param " +
				temporaryDir + s + "_listl "+
				temporaryDir + s + "*.str "+
				temporaryDir + s + "*.bpath "+
				temporaryDir + s + "*.cor "+
				temporaryDir + s + "*.fcor "+
				temporaryDir + s + "*.path "+
				temporaryDir + s + "*.sim "+
				temporaryDir + s + "_list "+
				temporaryDir + s + "_ll "+
				temporaryDir + s + "*.no "+
				temporaryDir + s + "*.tmpl ");

	}
	protected void importResult() throws Exception {
		Reader r = new BufferedReader(
				new FileReader(m_file_name+"_seq_pattern.dlf"));
		CorrelResultParser crp=new CorrelResultParser(r);
		m_correl_result=crp.parse();
	}
	protected void saveResult() throws Exception {
		CorrelResult2PLSql cr2sql=new CorrelResult2PLSql();
		cr2sql.setMetaData(m_md);
		cr2sql.setConnection(this.getM4Db());
		cr2sql.setResultName(m_result_name);
		cr2sql.convert(m_correl_result);
	}
	
	protected void setSampleTableName(String sampleTableName) {
		this.sampleTableName = sampleTableName;
	}
	
	protected String getSampleTableName() {
		return this.sampleTableName;
	}
	
};
/*
 * Historie
 * --------
 * 
 * $Log: CorrelWrapper.java,v $
 * Revision 1.4  2006/04/11 14:10:18  euler
 * Updated license text.
 *
 * Revision 1.3  2006/04/06 16:31:17  euler
 * Prepended license remark.
 *
 * Revision 1.2  2006/03/30 16:07:11  scholz
 * fixed author tags for release
 *
 * Revision 1.1  2006/01/03 09:54:36  hakenjos
 * Initial version!
 *
 */
