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

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import javax.swing.JFrame;

import edu.udo.cs.miningmart.db.ConfigReader;
import edu.udo.cs.miningmart.exception.M4Exception;
import edu.udo.cs.miningmart.m4.M4Interface;
import edu.udo.cs.miningmart.m4.core.M4InterfaceImpl;
import edu.udo.cs.miningmart.m4.utils.Print;

/**
 * An editor for the database-configuration.
 * @author Martin Scholz
 * @version $Id: DbConfigEditor.java,v 1.5 2006/04/11 14:10:18 euler Exp $
 */
public class DbConfigEditor {

	// constants naming the different variables used

	public static final String VAR_DB_NAME = "dbName";
	public static final String VAR_DB_HOST = "dbHost";
	public static final String VAR_DB_PORT = "dbPort";
	public static final String VAR_DB_DRIV = "jdbcDriver";

	public static final String VAR_M4_USER  = "m4User";
	public static final String VAR_M4_PASS  = "m4Pass";
	public static final String VAR_BUS_USER = "busUser";
	public static final String VAR_BUS_PASS = "busPass";

	// this array specifies which lines in the db.config file correspond to which variables
	String[] fileVars = {VAR_DB_NAME, VAR_M4_USER,  VAR_M4_PASS,  VAR_DB_DRIV, VAR_DB_HOST, null,
					     VAR_DB_NAME, VAR_BUS_USER, VAR_BUS_PASS, VAR_DB_DRIV, VAR_DB_HOST};

	// this map stores the variable values
	private final HashMap values = new HashMap();

	// this File is a path to dbConfig or <null> if the environment variable was not set etc.
	private final File dbConfig;

	// the main frame
	private final DbConfigEditorWindow frame;

	/** Constructor */
	public DbConfigEditor(JFrame parent) {
		String dbcFileS = System.getProperty(M4Interface.SYSTEM_PROP_DB_CONFIG_PATH);
		File f = null;
		if (dbcFileS != null && dbcFileS.length() > 0) {
			f = new File(dbcFileS);
			if (! f.exists() ) {
				try {
					f.createNewFile();							
				}
				catch (IOException e) {
					f = null;
				}
			}
			else if (! f.isFile()) {
				f = null;	
			}
		}		
		this.dbConfig = f;
		this.frame = new DbConfigEditorWindow(parent,values, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				save();
			}
		});
	}

	/** getter for variables stored in the HashMap */
	private String getValueFor(String variable) {
		return (String) this.values.get(variable);	
	}

	/** setter for variables stored in the HashMap */
	private void setVariable(String variable, String value) {
		this.values.put(variable, value);
	}


	/**
	 * Helper method reading the variables from dbConfig-file.
	 */
	private void readValues() {
		try {
			this.readValuesFromFile();	
			this.mapFileVariableToGui();					
		}
		catch (M4Exception e) {
			M4Interface.print.doPrint(Print.ERROR,e.getMessage(),e);
		}
	}

	private void readValuesFromFile() throws M4Exception {
			boolean exception = false;
			ConfigReader cfr = null;
			try {
				cfr = new ConfigReader(this.dbConfig.getAbsolutePath());
			}
			catch (M4Exception e) {
				exception = true; // use default values
			}
			
			//changed code after ConfigReader changed, though it is now
			// not so very elegant:
			
			// business db:
			this.setVariable(fileVars[0], exception ? "DBName" : cfr.getM4DbName());
			this.setVariable(fileVars[1], exception ? "M4User" :cfr.getM4User());
			this.setVariable(fileVars[2], exception ? "Password" :cfr.getM4Pw());
			String url = exception ? "@host.domain.de:1521:" : cfr.getM4Url();
			int atIndex = url.indexOf("@");
			int offset = 1;
			// for postgres, "//" is used instead of "@":
			if (atIndex == -1) {
				atIndex = url.indexOf("//");
				offset = 2;
			}
			String driver = url.substring(0, atIndex);
			String host = url.substring(atIndex + offset, url.length());
			this.setVariable(fileVars[3], driver);
			this.setVariable(fileVars[4], host);
			
			// M4 db:
			this.setVariable(fileVars[6], exception ? "DBName" :cfr.getBusDbName());
			this.setVariable(fileVars[7], exception ? "BusinessUser" :cfr.getBusUser());
			this.setVariable(fileVars[8], exception ? "Password" :cfr.getBusPw());
			url = exception ? "@host.domain.de:1521:" : cfr.getBusUrl();
			atIndex = url.indexOf("@");
			offset = 1;
			// for postgres, "//" is used instead of "@":
			if (atIndex == -1) {
				atIndex = url.indexOf("//");
				offset = 2;
			}
			driver = url.substring(0, atIndex);
			host = url.substring(atIndex + offset, url.length());
			this.setVariable(fileVars[9], driver);
			this.setVariable(fileVars[10], host);			
	}

	/**
	 * Method to do some translation of dbConfig-variables to GUI variables.
	 */
	private void mapFileVariableToGui() {
		final String hostAndPort = this.getValueFor(DbConfigEditor.VAR_DB_HOST);
		if (hostAndPort != null && hostAndPort.length() > 0) {
			int index = hostAndPort.indexOf(":");
			String host;
			String port;
			if (index == -1) {
				host = hostAndPort;
				port = "";	
			}
			else {
				host = hostAndPort.substring(0, index).trim();
				port = hostAndPort.substring(index + 1).trim();
			}
			if (host.startsWith("@")) {
				host = host.substring(1);
			}
			if (port.endsWith(":")) {
				port = port.substring(0, port.length() - 1);
			}
			this.setVariable(VAR_DB_HOST, host);
			this.setVariable(VAR_DB_PORT, port);
		}

		String jdbcDriver = this.getValueFor(DbConfigEditor.VAR_DB_DRIV);
		if (jdbcDriver != null && jdbcDriver.endsWith(":")) {
			jdbcDriver = jdbcDriver.substring(0, jdbcDriver.length() -1);
			this.setVariable(DbConfigEditor.VAR_DB_DRIV, jdbcDriver);
		}
	}

	/**
	 * This method writes back the values found in the local HashMap.
	 * It is called by the action associated to the save button.
	 */
	private void save() {		
		this.dbConfig.delete();
		FileWriter out = null;
		try {
			this.dbConfig.createNewFile();
			out = new FileWriter(this.dbConfig);
			String[] lines = new String[fileVars.length];
			for (int i=0; i<lines.length; i++) {
				String line = null;
				if (fileVars[i] != null) {
					line = this.getValueFor(fileVars[i]);
				}
				lines[i] = (line == null ? "" : line);
			}

			String host = lines[4].trim();
			String port = this.getValueFor(VAR_DB_PORT);
			if (!host.startsWith("@")) {
				host = "@" + host;
			}
			if (port != null) {	
				port = port.trim();
				if (port.startsWith(":")) {
					host += port;	
				}
				else host += ":" + port;
			}
			if (!host.endsWith(":")) {
				host += ":";
			}
			lines[4]  = host;
			lines[10] = host;

			String jdbcDriver = lines[3].trim();
			if (!jdbcDriver.endsWith(":")) {
				jdbcDriver = jdbcDriver + ":";
			}
			lines[3] = jdbcDriver;
			lines[9] = jdbcDriver;

			for (int i=0; i<lines.length; i++) {
				out.write(lines[i] + "\n");
			}
		}
		catch (IOException e) {
			M4Interface.print.doPrint(Print.ERROR,e.getMessage(),e);
		}
		finally {
			try {
				if (out != null)
					out.close();	
			}
			catch (IOException e) {}
		}
		
		M4InterfaceImpl m4i = (M4InterfaceImpl) M4InterfaceImpl.getInstance();
		if (m4i != null) {
			m4i.getNewDbConnection();
		}
	}

	/**
	 * This method reads the settings from file and initialises
	 * the editor frame.
	 */
	public void init() {
		if (this.dbConfig == null) {
			System.err.println(
			"Could not find db.config file. Please make sure the environment variable '"
			+ M4Interface.SYSTEM_PROP_DB_CONFIG_PATH
			+ "' is set and that the specified file is accessible.");
			return;	
		}
		this.readValues();
		this.frame.setRestartWarning(this.showRestartWarning);
		this.frame.prepareWindow();
		this.frame.setVisible(true);		
	}
	
	private boolean showRestartWarning;

	/** Method to turn on/off the restart warning after changing the db.config settings. */
	public void setRestartWarning(boolean showRestartWarning) {
		this.showRestartWarning = showRestartWarning;	
	}

	public boolean frameActive() {
		return this.frame.isActive();	
	}	
	
	public boolean shouldRestart(){
		return frame.shouldRestart();
	}
	
	public boolean isCanceled() {
		return frame.isCanceled();
	}
	
}
/*
 * Historie
 * --------
 *
 * $Log: DbConfigEditor.java,v $
 * Revision 1.5  2006/04/11 14:10:18  euler
 * Updated license text.
 *
 * Revision 1.4  2006/04/06 16:31:17  euler
 * Prepended license remark.
 *
 * Revision 1.3  2006/03/29 09:50:47  euler
 * Added installation robustness.
 *
 * Revision 1.2  2006/03/19 17:00:16  scholz
 * robustification against missing or invalid db.config file
 *
 * Revision 1.1  2006/01/03 09:54:34  hakenjos
 * Initial version!
 *
 */
