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

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Serializable;

import edu.udo.cs.miningmart.exception.M4Exception;

/**
 * Class to read and hold infos from the MiningMart DB configuration file.
 * 
 * @author Timm Euler, Martin Scholz
 * @version $Id: ConfigReader.java,v 1.7 2006/04/11 14:10:16 euler Exp $
 */
public class ConfigReader implements Serializable {
	
	// names of the properties in the db.config file
	public static final String M4_DRIVER = "M4_JDBC_DRIVER";
	public static final String M4_LOCATION = "M4_HOST_PORT";
	public static final String M4_DBNAME = "M4_DBNAME";
	public static final String M4_USER = "M4_USER";
	public static final String M4_PW = "M4_PASSWORD";
	public static final String BUS_DRIVER = "BUS_JDBC_DRIVER";
	public static final String BUS_LOCATION = "BUS_HOST_PORT";
	public static final String BUS_DBNAME = "BUS_DBNAME";
	public static final String BUS_USER = "BUS_USER";
	public static final String BUS_PW = "BUS_PASSWORD";
	
    private String m4Url;
    private String m4Driver;
    private String m4Host;
    private String m4DbName;
    private String m4User;
    private String m4Pw;
    private String busUrl;
    private String busDriver;
    private String busHost;
    private String busDbName;
    private String busUser;
    private String busPw;    

    /**
     * Constructor needs the filename with path.
     *
     * @param configFileName A String with the path and name of the configuration
     *        file.
     */
    public ConfigReader(String configFileName) throws M4Exception {
    	
    	String errMsg = "(I/O) Error trying to read Db config file '" + configFileName + "': ";
    	
    	try {
    		LineNumberReader myLineReader = new LineNumberReader(new FileReader(configFileName));
    		String myLine = myLineReader.readLine();
    		
    		if (myLine == null) {
    			throw new M4Exception(errMsg + "Nothing found in the file.");
    		}    		
    		
    		// skip comment and empty lines:
    		while (myLine != null && (myLine.trim().equals("") || myLine.trim().startsWith("#"))) { 
    			myLine = myLineReader.readLine();
    		}
    		if (myLine == null) {
    			throw new M4Exception(errMsg + "No information found in the file.");
    		}    		
    			
    		// To be downwards compatible, we allow the old 
    		// db.config format:
    		if (myLine.indexOf("=") == -1) { // no key-value pair
    			this.readOldFormatDbConfig(myLineReader, myLine, errMsg);
    		}
    		else {
    			// read key-value pairs:
    			while (myLine != null) {
    				this.readKeyValuePair(myLine, errMsg);
    				myLine = myLineReader.readLine();
    	    		// skip comment and empty lines:
    	    		while (myLine != null && (myLine.equals("") || myLine.startsWith("#"))) { 
    	    			myLine = myLineReader.readLine();
    	    		}
    			}
    			// get the DB URLs:
    			if (this.m4Driver != null && this.m4Host != null 
				    && this.busDriver != null && this.busHost != null) {
    				this.m4Url = this.m4Driver + this.m4Host;
    				this.busUrl = this.busDriver + this.busHost;
    			}
    		}
			// check completeness of information:
			if ( this.busDbName == null || this.busPw == null ||
				 this.busUrl == null || this.busUser == null ||
				 this.m4DbName == null || this.m4Pw == null ||
				 this.m4Url == null || this.m4User == null) {
				throw new M4Exception(errMsg + "Not all information was found!");
			}
    		// close the reader:
    		myLineReader.close();
    	}
    	catch (IOException ioe) {
    		throw new M4Exception(errMsg + ioe.getMessage());
    	}
    }
    
    private void readKeyValuePair(String line, String errMsg) throws M4Exception {
    	int indexOfEqualSign = line.indexOf("=");
    	if (indexOfEqualSign == -1) {
    		throw new M4Exception(errMsg + "Invalid key-value pair, line: " + line);
    	}
    	String key = line.substring(0, indexOfEqualSign).trim();
    	String value = null;
    	if (line.length() > indexOfEqualSign+1) {
    		value = line.substring(indexOfEqualSign + 1).trim();
    	}
    	if (value == null || value.equals("")) {
    		throw new M4Exception(errMsg + "Empty value for key '" + key + "'!");
    	}
    	
    	if (key.equals(M4_DBNAME)) {
    		this.m4DbName = value;
    	}
    	else if (key.equals(M4_USER)) {
    		this.m4User = value;
    	}
    	else if (key.equals(M4_DRIVER)) {
    		this.m4Driver = value;
    	}
    	else if (key.equals(M4_LOCATION)) {
    		this.m4Host = value;
    	}
    	else if (key.equals(M4_PW)) {
    		this.m4Pw = value;
    	}
    	else if (key.equals(BUS_DBNAME)) {
    		this.busDbName = value;
    	}
    	else if (key.equals(BUS_USER)) {
    		this.busUser = value;
    	}
    	else if (key.equals(BUS_DRIVER)) {
    		this.busDriver = value;
    	}
    	else if (key.equals(BUS_LOCATION)) {
    		this.busHost = value;
    	}
    	else if (key.equals(BUS_PW)) {
    		this.busPw = value;
    	}
    	else throw new M4Exception(errMsg + "Unknown key found in this line: " + line);
    }
    
    private void readOldFormatDbConfig(LineNumberReader lnr, String firstLine, String errMsg)
    throws M4Exception {
    	// read m4 config data:
    	this.m4DbName = firstLine;
    	this.m4User = this.getNextLine(lnr, errMsg);
    	this.m4Pw = this.getNextLine(lnr, errMsg);
    	this.m4Url = this.getNextLine(lnr, errMsg) + this.getNextLine(lnr, errMsg);
		    		
    	// read separating line:
    	String myLine = null;
    	try {
    		myLine = lnr.readLine();
    	}
    	catch (IOException ioe) {
    		throw new M4Exception(errMsg + ioe.getMessage());
    	}
    	if ((myLine == null) || ( ! myLine.trim().equals(""))) {
    		throw new M4Exception(errMsg + "Wrong file format: expected one empty line between M4 and Business connection infos!");
    	}
		    		
    	// read business config data:
    	this.busDbName = this.getNextLine(lnr, errMsg);
    	this.busUser = this.getNextLine(lnr, errMsg);
    	this.busPw = this.getNextLine(lnr, errMsg);
    	this.busUrl = this.getNextLine(lnr, errMsg) + this.getNextLine(lnr, errMsg);    	
    }

    private String getNextLine(LineNumberReader lnr, String errMsg) throws M4Exception {
    	try {
    		String line = lnr.readLine();
    		if (line == null) {
    			throw new M4Exception(errMsg + "Unexpected end of file.");
    		}    		
    		if (line.trim().equals("")) {
    			throw new M4Exception(errMsg + "Wrong file format, found empty line where information was expected.");
    		}
    		return line.trim();
    	}
    	catch (IOException ioe) {
    		throw new M4Exception(errMsg + ioe.getMessage());			
    	}
    } 
     
	/**
	 * @return Returns the DbName for the business data connection.
	 */
	public String getBusDbName() {
		return busDbName;
	}
	
	/**
	 * @return Returns the Password for the business data connection.
	 */
	public String getBusPw() {
		return busPw;
	}
	
	/**
	 * @return Returns the Url for the business data connection.
	 */
	public String getBusUrl() {
		return busUrl;
	}
	
	/**
	 * @return Returns the username for the business data connection.
	 */
	public String getBusUser() {
		return busUser;
	}
	
	/**
	 * @return Returns the DbName for the M4 data connection.
	 */
	public String getM4DbName() {
		return m4DbName;
	}
	
	/**
	 * @return Returns the Password for the M4 data connection.
	 */
	public String getM4Pw() {
		return m4Pw;
	}
	
	/**
	 * @return Returns the Url for the M4 data connection.
	 */
	public String getM4Url() {
		return m4Url;
	}
	
	/**
	 * @return Returns the username for the M4 data connection.
	 */
	public String getM4User() {
		return m4User;
	}
}
/*
 * Historie
 * --------
 *
 * $Log: ConfigReader.java,v $
 * Revision 1.7  2006/04/11 14:10:16  euler
 * Updated license text.
 *
 * Revision 1.6  2006/04/06 16:31:15  euler
 * Prepended license remark.
 *
 * Revision 1.5  2006/03/30 16:07:15  scholz
 * fixed author tags for release
 *
 * Revision 1.4  2006/03/29 09:50:47  euler
 * Added installation robustness.
 *
 * Revision 1.3  2006/01/26 14:57:27  euler
 * Updates
 *
 * Revision 1.2  2006/01/25 12:54:29  euler
 * Skips comments in db.config file now.
 *
 * Revision 1.1  2006/01/03 09:54:22  hakenjos
 * Initial version!
 *
 */
