/*
 * 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.m4.utils;

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import edu.udo.cs.miningmart.db.DB;
import edu.udo.cs.miningmart.exception.DbConnectionClosed;
import edu.udo.cs.miningmart.exception.M4Exception;
import edu.udo.cs.miningmart.m4.BaseAttribute;
import edu.udo.cs.miningmart.m4.Case;
import edu.udo.cs.miningmart.m4.Columnset;
import edu.udo.cs.miningmart.m4.Concept;
import edu.udo.cs.miningmart.m4.ConceptualDatatypes;
import edu.udo.cs.miningmart.m4.RelationalDatatypes;

/**
 * This class can be used to create metadata in M4 for given table names
 * in the business data. A file with the table names can be specified
 * as the first argument for the main method. The tool creates a columnset,
 * columns, BaseAttributes and a Concept with the names found in the database.
 * The case id to which the metadata should belong is the second argument
 * of the main method.
 * The method is DBMS-dependent, that is, it only works for Oracle at the
 * moment.
 * 
 * @author Timm Euler
 * @version $Id: CreateConceptsTool.java,v 1.3 2006/04/11 14:10:09 euler Exp $
 */
public class CreateConceptsTool {
	private String tableNamesFile;
	private DB m4db;
	private Case myCase;
	private String schema;
	
	/**
	 * Constructor for CreateConceptsTool. Needs the DB information object ,
	 * the name of the business schema and the Case object. The business schema name
	 * is used for new Columnsets.
	 * 
	 * @param theDb DB information
	 * @param schemaName name of the business DB schema
	 * @param theCase All metadata to be created will belong to this Case
	 */
	public CreateConceptsTool(DB theDb, String schemaName, Case theCase) {
		this.m4db = theDb;
		this.schema = schemaName;
		this.myCase = theCase;
	}
	
	/**
	 * Creates columnset, columns, baseattributes and concepts for 
	 * each table or view whose name is in the given Collection (if it is a 
	 * valid database object's name).
	 *
	 * @param theTableNames a Collection of Strings
	 * @return a Collection of Concepts
	 */
	public Collection createConcepts(Collection theTableNames) throws M4Exception {
		Vector theConcepts = new Vector();
		// pretend that we create only Columnsets for Tables for the moment:
		boolean isATable = true;
		if (theTableNames != null) {
			Iterator it = theTableNames.iterator();
			while (it.hasNext()) {	
				Concept newConcept = createConcept((String) it.next(), isATable);
				 theConcepts.add(newConcept);
			}
			theConcepts.trimToSize();
		}
		return theConcepts;
	}
	
	private Collection getTableNames(String fileName)
	{
		try
		{
			LineNumberReader lnr = new LineNumberReader(new FileReader(fileName));
			String line = lnr.readLine();
			Vector v = new Vector();
			while (line != null)
			{
				v.add(line.trim());
				line = lnr.readLine();
			}
			v.trimToSize();
			lnr.close();
			return v;	
		}
		catch (IOException ioe)
		{   System.out.println("CreateConceptsTool: Error accessing file with table names: " + ioe.getMessage());  
			System.exit(-1);
		}
		return null;
	}
	
	// creates a Concept that is connected to the DB object (table or view) with the given name.
	// The Concept belongs to the Case specified in the constructor of this CreateConceptsTool object.
	// The boolean isTable indicates whether the DB object is a table (TRUE) or a view (FALSE).
	private Concept createConcept(String tableName, boolean isTable) throws M4Exception {
		try {
			// use a special query that returns the names of the columns:
			String query = this.m4db.getSelectStringAllColumnsForDbObject(tableName);
			ResultSet rs = this.m4db.executeBusinessSqlRead(query);
			// but we need the meta data object anyway for the column types:
			ResultSetMetaData rsmd = rs.getMetaData();
			int noOfColumns = rsmd.getColumnCount();
			String[] theColumnNames = new String[noOfColumns];
			String[] theColumnTypes = new String[noOfColumns];
			String[] theConceptualTypes = new String[noOfColumns];
			for (int i = 1; i <= noOfColumns; i++) { // column count starts with 1
				theColumnNames[i-1] = rsmd.getColumnName(i);
				String dbmsType = rsmd.getColumnTypeName(i);
				theColumnTypes[i-1] = this.m4db.getM4RelationalDatatypeName(dbmsType, true);
				theConceptualTypes[i-1] = this.getBaTypeForColumnType(theColumnTypes[i-1]);				
			}
			
			rs.close();
						
			// create the concept and columnset:
			Concept newConcept = this.myCase.createConcept(tableName, Concept.TYPE_DB);
			String csType = (isTable ? Columnset.CS_TYPE_TABLE : Columnset.CS_TYPE_VIEW);
			Columnset newColumnset = newConcept.createColumnset(tableName, this.schema, csType);
			
			// create the columns and BaseAttributes
			for (int i = 0; i < noOfColumns; i++) {
				newConcept.createBaseAttribute(theColumnNames[i], theConceptualTypes[i], BaseAttribute.TYPE_DB);
				newColumnset.createColumn(theColumnNames[i], theColumnTypes[i]);
			}
			
			return newConcept;
		}
		catch (SQLException sqle)
		{   throw new M4Exception("CreateConceptsTool: SQL Error reading information about the Columns: " + sqle.getMessage());
		}
		catch (DbConnectionClosed dbc)
		{   throw new M4Exception("CreateConceptsTool: DB connection closed: " + dbc.getMessage());
		}
	}
	
	// returns an M4 ConceptualDataType that can be used for a BaseAttribute which is
	// connected to a Column with the given M4 RelationalDataType
	private String getBaTypeForColumnType(String colType) {
		if (colType.equals(RelationalDatatypes.RELATIONAL_DATATYPE_NUMBER)) {
			return ConceptualDatatypes.CDT_NUMERIC;
		}
		if (colType.equals(RelationalDatatypes.RELATIONAL_DATATYPE_STRING)) {
			return ConceptualDatatypes.CDT_CATEGORIAL;
		}
		if (colType.equals(RelationalDatatypes.RELATIONAL_DATATYPE_KEY)) {
			return ConceptualDatatypes.CDT_CATEGORIAL;
		}
		if (colType.equals(RelationalDatatypes.RELATIONAL_DATATYPE_DATE)) {
			return ConceptualDatatypes.CDT_TIME;
		}
		return null; // cannot happen
	}
}
/*
 * Historie
 * --------
 * 
 * $Log: CreateConceptsTool.java,v $
 * Revision 1.3  2006/04/11 14:10:09  euler
 * Updated license text.
 *
 * Revision 1.2  2006/04/06 16:31:09  euler
 * Prepended license remark.
 *
 * Revision 1.1  2006/01/03 09:54:03  hakenjos
 * Initial version!
 *
 */
