/*
 * 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.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.musoft.limo.application.Resource;

import edu.udo.cs.miningmart.m4.M4Interface;
import edu.udo.cs.miningmart.m4.utils.Print;

/**
 * A JDialog for editing the database-configuration.
 * @author Martin Scholz
 * @version $Id: DbConfigEditorWindow.java,v 1.5 2006/04/11 14:10:18 euler Exp $
 */
public class DbConfigEditorWindow extends JDialog {

	// Semantics of fields: {VariableName, NameUsedInGui, Default}
	private static final String[][] mapping = new String[][] {
		{DbConfigEditor.VAR_DB_NAME, Resource.getString("DBCONFIG_DB_NAME"), null,},
		{DbConfigEditor.VAR_DB_DRIV, Resource.getString("DBCONFIG_DB_DRIVER"), "jdbc:oracle:thin:"},
		{DbConfigEditor.VAR_DB_HOST, Resource.getString("DBCONFIG_DB_HOST"), null},
		{DbConfigEditor.VAR_DB_PORT, Resource.getString("DBCONFIG_DB_PORT"), "1521"},
	
		{null, "", null},  // separator line
		    
		{DbConfigEditor.VAR_M4_USER,  Resource.getString("DBCONFIG_M4_USER"),           null},
		{DbConfigEditor.VAR_M4_PASS,  Resource.getString("DBCONFIG_M4_PASS"),       null},
		{DbConfigEditor.VAR_BUS_USER, Resource.getString("DBCONFIG_BUS_USER"),         null},
		{DbConfigEditor.VAR_BUS_PASS, Resource.getString("DBCONFIG_BUS_PASS"), null}
	};

	// ***** Instance fields *****
	private final HashMap values;
	private final ActionListener saveAction;
	private JPanel panel;
	private JTextField[] theGuiValues;
	private boolean restart=false;
	private boolean canceled = true;
	private boolean showRestartWarning;
	
	// *** Constructor ***
	public DbConfigEditorWindow(JFrame parent,HashMap values, ActionListener saveAction) {
		super(parent,Resource.getString("DBCONFIG_TITLE"),true);
		this.values = values;
		this.saveAction = saveAction;
	}	

	// *** Getter and setter ***
	
	private String getValueFor(String variable) {
		return (String) this.values.get(variable);	
	}

	private void setVariable(String variable, String value) {
		this.values.put(variable, value);
	}

	// *** init ***
	public void prepareWindow() {//throws IOException {
		if (this.panel == null) {
			this.panel = this.createMainPanel();
			this.getContentPane().add(this.panel);
		}
		else {
			this.setValues();	
		}
		this.pack();
		
		Dimension size=this.getSize();

		this.setLocation(
        (Toolkit.getDefaultToolkit().getScreenSize().width-
         size.width) / 2,
        (Toolkit.getDefaultToolkit().getScreenSize().height-
         size.height) / 2);
		
		this.canceled = true;
	}

	/** 
	 * Writes back all the variables from the text fields and saves them
	 * using the ActionListener given to the constructor.
	 * */
	void saveButtonAction() {
		this.canceled = false;
		
		if (this.saveAction != null) {
			for (int i=0; i<mapping.length; i++) {
				String var = mapping[i][0];
				if (var != null) {
					String value = this.theGuiValues[i].getText().trim();
					this.values.put(var, value);
				}	
			}
			this.saveAction.actionPerformed(null);
		}
		this.dispose();

		if (this.showRestartWarning) {
			restart=true;
			M4Interface.print.doPrint(Print.MAX,Resource.getString("DBCONFIG_RESTART_MSG1")+"\n \t\t"+Resource.getString("DBCONFIG_RESTART_MSG2") );
			JOptionPane.showMessageDialog(null,
		   		Resource.getString("DBCONFIG_RESTART_MSG1")+"\n"+
		   		Resource.getString("DBCONFIG_RESTART_MSG2"),
		   		Resource.getString("DBCONFIG_RESTART_TITLE"),
		   		JOptionPane.INFORMATION_MESSAGE);
		}
		this.cancelButtonAction();
	}

	/** Clean up and close this Frame. */
	void cancelButtonAction() {
		this.dispose();
		this.values.clear();
	}

	/** Helper method doing all the preparation of the Frame. */
	private JPanel createMainPanel() {//throws IOException {
		final int mappingLength = DbConfigEditorWindow.mapping.length;
		this.theGuiValues = new JTextField[mappingLength];
		JPanel theFields = new JPanel();
		{
			JPanel theNames = new JPanel();
			JPanel theValues = new JPanel();
			
			theNames.setLayout(new GridLayout(mappingLength, 1));
			theValues.setLayout(new GridLayout(mappingLength, 1));
			for (int i=0; i<mappingLength; i++) {
				final String[] currentMapping = DbConfigEditorWindow.mapping[i];
				String name = currentMapping[1];

				JTextField valueTa;
				if (currentMapping[0] != null) {
					JLabel nameTa = new JLabel(name);
					//nameTa.setEditable(false);
					theNames.add(nameTa);
					String value = this.getValueFor(currentMapping[0]);
					if (value == null || value.length() == 0) {
						value = currentMapping[2];
						if (value == null) {
							value = "";	
						}
					}
					if (currentMapping[0].equals(DbConfigEditor.VAR_M4_PASS)
					 || currentMapping[0].equals(DbConfigEditor.VAR_BUS_PASS))
					{
						valueTa = new JPasswordField(value, 40);
					}
					else valueTa = new JTextField(value, 40);
					
					valueTa.setEditable(true);
					theValues.add(valueTa);
				}
				else {
					theNames.add(new JPanel());
					theValues.add(new JPanel());
					valueTa = new JTextField("", 40);
				}
				this.theGuiValues[i] = valueTa;				
			}
			theFields.setLayout(new BorderLayout(5,5));
			theFields.add(theNames, BorderLayout.WEST);
			theFields.add(theValues, BorderLayout.CENTER);
		}
		
		JPanel theButtons = new JPanel();
		{
			theButtons.setLayout(new BorderLayout(5,5));
			JPanel center = new JPanel();
			center.setLayout(new BoxLayout(center,BoxLayout.X_AXIS));
			JButton saveButton = new JButton(Resource.getString("SAVE"));
			JButton cancelButton = new JButton(Resource.getString("CANCEL"));
			center.add(saveButton);
			center.add(cancelButton);
			theButtons.add(center, BorderLayout.EAST);
			saveButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					saveButtonAction();
				}
			});
			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					cancelButtonAction();
				}
			});
		}
		
		JPanel panel = new JPanel();
		{			
			panel.setLayout(new BorderLayout(5,5));
			panel.add(theFields, BorderLayout.NORTH);
			panel.add(theButtons, BorderLayout.SOUTH);
		}
		panel.setBorder(BorderFactory.createEmptyBorder(20,10,5,10));
		return panel;
	}

	private void setValues() {
		for (int i=0; i<DbConfigEditorWindow.mapping.length; i++) {
			final String[] currentMapping = DbConfigEditorWindow.mapping[i];
			final String varName = currentMapping[0];
			if (varName != null) {
				String value = this.getValueFor(varName);
				if (value == null || value.length() == 0) {
					value = currentMapping[2];
					if (value == null) {
						value = "";	
					}
				}
				this.theGuiValues[i].setText(value);
			}
		}
	}
	
	public boolean isCanceled() {
		return this.canceled;
	}

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

}
/*
 * Historie
 * --------
 *
 * $Log: DbConfigEditorWindow.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!
 *
 */
