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

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.musoft.limo.application.Resource;

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.gui.application.MiningMartApplication;
import edu.udo.cs.miningmart.gui.model.MiningMartConcept;
import edu.udo.cs.miningmart.gui.model.MiningMartRelation;
import edu.udo.cs.miningmart.gui.stepsettings.ListSelectDialog;
import edu.udo.cs.miningmart.m4.BaseAttribute;
import edu.udo.cs.miningmart.m4.Case;
import edu.udo.cs.miningmart.m4.Column;
import edu.udo.cs.miningmart.m4.Columnset;
import edu.udo.cs.miningmart.m4.Concept;
import edu.udo.cs.miningmart.m4.ForeignKey;
import edu.udo.cs.miningmart.m4.ForeignKeyLink;
import edu.udo.cs.miningmart.m4.M4Interface;
import edu.udo.cs.miningmart.m4.Relation;
import edu.udo.cs.miningmart.m4.utils.Print;

/**
 * A <code>JDialog</code> to create a new <code>Relation</code>.
 * @author Daniel Hakenjos
 * @version $Id: CreateRelationDialog.java,v 1.11 2006/04/11 14:10:16 euler Exp $
 */
public class CreateRelationDialog extends JDialog implements ActionListener, ListSelectionListener{

	public static final int CANCEL = 0;
	public static final int OK = 1;
	
	private int exitAction;
	
	private MiningMartApplication app;
	
	private MiningMartConcept fromconcept, toconcept;

	private MiningMartRelation mmartrelation;

	private Relation relation;
	
	private JButton cancelButton,okButton, foreignKeyButton1, foreignKeyButton2;
	
	private JRadioButton one2manyButton, many2manyButton;
	
	private JTextField nameField;
	
	private JList fromlist, tolist,crosslist;
	
	private JList fromattlist,toattlist;
	
	private JPanel fromlistPanel,tolistPanel,crosslistPanel, attlistPanel;
	
	private JLabel fromlabel,tolabel, crosslabel1, crosslabel2, fromattlabel, toattlabel, crossattlabel;
	
	private boolean tablesloaded;
	
	private boolean tableselected;
	
	public CreateRelationDialog(MiningMartApplication app, MiningMartConcept fromconcept, MiningMartConcept toconcept){
		super(app,Resource.getString("CREATE_RELATION_DIALOG_TITLE"),true);

		this.app=app;
		this.fromconcept=fromconcept;
		this.toconcept=toconcept;
		this.mmartrelation=null;
		this.relation=null;
		this.tablesloaded=false;
		this.tableselected=false;

		initComponents(false);		
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

		this.pack();

		setSize(850, 450);

		Dimension size = this.getSize();

		this.setLocation(
			(Toolkit.getDefaultToolkit().getScreenSize().width - size.width)
				/ 2,
			(Toolkit.getDefaultToolkit().getScreenSize().height - size.height)
				/ 2);
		this.setVisible(true);
	}
	
	public CreateRelationDialog(MiningMartApplication app, MiningMartRelation relation){
		super(app,Resource.getString("EDIT_RELATION_DIALOG_TITLE"),true);

		this.app=app;
		this.fromconcept=(MiningMartConcept) relation.getStart();
		this.toconcept=(MiningMartConcept) relation.getEnd();
		this.mmartrelation=relation;
		this.relation=relation.getRelation();
		this.tablesloaded=false;
		this.tableselected=false;

		initComponents(true);
		
		boolean relationalLevelExists = fillComponents();
		if ( ! relationalLevelExists) {
			JOptionPane.showMessageDialog(
				this.app,
				Resource.getString("INFO_NO_COLS_RELATION_MSG"),
				Resource.getString("INFO_NO_COLS_RELATION_TITLE"),
				JOptionPane.INFORMATION_MESSAGE);
		}
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

		this.pack();

		setSize(850, 450);

		Dimension size = this.getSize();

		this.setLocation(
			(Toolkit.getDefaultToolkit().getScreenSize().width - size.width)
				/ 2,
			(Toolkit.getDefaultToolkit().getScreenSize().height - size.height)
				/ 2);
		this.setVisible(true);
	}
	
	
	private void initComponents(boolean edit){
		JPanel toppanel=new JPanel();
		toppanel.setLayout(new BorderLayout(15,15));
		toppanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		this.getContentPane().add(toppanel);
		
		//Titel
		JLabel toplabel=new JLabel();
		String toplabelText = (edit ? Resource.getString("EDIT_RELATION_DIALOG_SUBTITLE") : Resource.getString("CREATE_RELATION_DIALOG_SUBTITLE"));
		toplabel.setText(toplabelText);

		Font opfont=new Font("SansSerif",Font.PLAIN,15);
		toplabel.setFont(opfont);
		toplabel.setForeground(Color.BLUE);
		toplabel.setHorizontalAlignment(SwingConstants.CENTER);	
		toplabel.setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
		toppanel.add(toplabel,BorderLayout.NORTH);

		//Buttons
		cancelButton = new JButton(Resource.getString("CANCEL"));
		okButton = new JButton(Resource.getString("OK"));
		okButton.setEnabled(true);

		cancelButton.addActionListener(this);
		okButton.addActionListener(this);

		JPanel bottom = new JPanel();
		bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
		bottom.add(Box.createHorizontalGlue());
		bottom.add(okButton);
		bottom.add(Box.createRigidArea(new Dimension(10, 0)));
		bottom.add(cancelButton);
		bottom.setBorder(BorderFactory.createEmptyBorder(0,5,5,5));
		toppanel.add(bottom, BorderLayout.SOUTH);	

		//Input
		JPanel midpanel=new JPanel();
		midpanel.setLayout(new BorderLayout(15,15));
		//midpanel.setBorder(BorderFactory.createEtchedBorder());
		toppanel.add(midpanel,BorderLayout.CENTER);
		
		JPanel inputPanel1=new JPanel();
		inputPanel1.setLayout(new BorderLayout());
		midpanel.add(inputPanel1,BorderLayout.NORTH);
		
		JPanel inputPanel2=new JPanel();
		inputPanel2.setLayout(new GridLayout(2,1,5,5));
		inputPanel1.add(inputPanel2,BorderLayout.WEST);
		
		JPanel inputPanel3=new JPanel();
		inputPanel3.setLayout(new BorderLayout(5,5));
		inputPanel2.add(inputPanel3);
		inputPanel3.add(new JLabel("Type:"), BorderLayout.WEST);		
		
		JPanel inputPanel4=new JPanel();
		inputPanel4.setLayout(new GridLayout(1,2,5,5));		
		inputPanel3.add(inputPanel4,BorderLayout.CENTER);
		one2manyButton=new JRadioButton(Resource.getString("ONE_TO_MANY_RELATION"));
		many2manyButton=new JRadioButton(Resource.getString("MANY_TO_MANY_RELATION"));
		ButtonGroup bGroup = new ButtonGroup();
		bGroup.add(one2manyButton);
		bGroup.add(many2manyButton);
		one2manyButton.setSelected(true);
		one2manyButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event){
				if (one2manyButton.isSelected()){
					setOne2ManyType();
				}else{
					setMany2ManyType();
				}
			}
		});
		many2manyButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event){
				if (one2manyButton.isSelected()){
					setOne2ManyType();
				}else{
					setMany2ManyType();
				}
			}
		});
		inputPanel4.add(one2manyButton);		
		inputPanel4.add(many2manyButton);		

		inputPanel3=new JPanel();
		inputPanel3.setLayout(new BorderLayout(5,5));
		inputPanel2.add(inputPanel3);
		inputPanel3.add(new JLabel(Resource.getString("ATTR_NAME")+":"), BorderLayout.WEST);		
		nameField=new JTextField();
		nameField.setText(Resource.getString("RELATION"));
		nameField.setPreferredSize(new Dimension(150,nameField.getHeight()));
		inputPanel3.add(nameField,BorderLayout.CENTER);
		
		JPanel listPanel=new JPanel();
		listPanel.setLayout(new GridLayout(1,4,10,10));
		midpanel.add(listPanel,BorderLayout.CENTER);
		
		fromlistPanel=new JPanel();
		fromlistPanel.setLayout(new BorderLayout(5,5));
		fromlist=new JList();
		fromlist.setVisibleRowCount(10);
		fromlistPanel.add(new JScrollPane(fromlist),BorderLayout.CENTER);
		JPanel labelPanel=new JPanel();
		labelPanel.setLayout(new GridLayout(2,1));
		fromlistPanel.add(labelPanel,BorderLayout.NORTH);		
		Concept concept=fromconcept.getConcept();
		labelPanel.add(new JLabel(Resource.getString("FROM_CONCEPT")+" "+concept.getName()));
		fromlabel=new JLabel(Resource.getString("FOREIGNKEYS")+":");
		labelPanel.add(fromlabel);
		JButton selectButton=new JButton(Resource.getString("SELECT")+"...");		
		selectButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event){
				Concept concept=fromconcept.getConcept();
				Collection bas=null;
				try {
					bas = concept.getAllBaseAttributes();
				} catch (M4Exception e) {
					bas=new LinkedList();
				}
				String[] data=new String[bas.size()];
				Iterator iter=bas.iterator();
				int index=0;
				while(iter.hasNext()){
					 data[index]=((BaseAttribute) iter.next()).getName();
					 index++;
				}
				
				ListModel model=fromlist.getModel();
				
				String[] selected_data=new String[model.getSize()];
				for(int i=0;i<selected_data.length;i++){
					selected_data[i]=(String) model.getElementAt(i);
				}

				ListSelectDialog dialog=new ListSelectDialog(app,Resource.getString("FEATURE_DIALOG_TITLE"),Resource.getString("FEATURE_DIALOG_SUBTITLE"),data,selected_data,true,0,Integer.MAX_VALUE);
				if (dialog.getExitAction()==ListSelectDialog.OK){
					selected_data=dialog.getSelectedDataItems();
					fromlist.setListData(selected_data);
				}
			}
		});
		JPanel buttonPanel=new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(selectButton);
		fromlistPanel.add(buttonPanel,BorderLayout.SOUTH);
		listPanel.add(fromlistPanel);

		tolistPanel=new JPanel();
		tolistPanel.setLayout(new BorderLayout(5,5));
		concept=toconcept.getConcept();
		tolist=new JList();
		tolist.setVisibleRowCount(10);
		tolistPanel.add(new JScrollPane(tolist),BorderLayout.CENTER);
		labelPanel=new JPanel();
		labelPanel.setLayout(new GridLayout(2,1));
		tolistPanel.add(labelPanel,BorderLayout.NORTH);		
		labelPanel.add(new JLabel(Resource.getString("TO_CONCEPT")+" "+concept.getName()));
		tolabel=new JLabel(Resource.getString("PRIMARYKEYS")+":");
		labelPanel.add(tolabel);		
		selectButton=new JButton(Resource.getString("SELECT")+"...");		
		selectButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event){
				Concept concept=toconcept.getConcept();
				Collection bas=null;
				try {
					bas = concept.getAllBaseAttributes();
				} catch (M4Exception e) {
					bas=new LinkedList();
				}
				String[] data=new String[bas.size()];
				Iterator iter=bas.iterator();
				int index=0;
				while(iter.hasNext()){
					 data[index]=((BaseAttribute) iter.next()).getName();
					 index++;
				}

				ListModel model=tolist.getModel();
				
				String[] selected_data=new String[model.getSize()];
				for(int i=0;i<selected_data.length;i++){
					selected_data[i]=(String) model.getElementAt(i);
				}

				ListSelectDialog dialog=new ListSelectDialog(app,Resource.getString("FEATURE_DIALOG_TITLE"),Resource.getString("FEATURE_DIALOG_SUBTITLE"),data,selected_data,true,0,Integer.MAX_VALUE);
				if (dialog.getExitAction()==ListSelectDialog.OK){
					selected_data=dialog.getSelectedDataItems();
					tolist.setListData(selected_data);
				}
			}
		});
		buttonPanel=new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(selectButton);
		tolistPanel.add(buttonPanel,BorderLayout.SOUTH);
		listPanel.add(tolistPanel);
		
		crosslistPanel=new JPanel();
		crosslistPanel.setLayout(new BorderLayout());
		labelPanel=new JPanel();
		labelPanel.setLayout(new GridLayout(2,1));
		crosslistPanel.add(labelPanel,BorderLayout.NORTH);	
		crosslabel1=new JLabel(Resource.getString("SELECT"));	
		labelPanel.add(crosslabel1);
		crosslabel2=new JLabel(Resource.getString("CROSSTABLE"));
		labelPanel.add(crosslabel2);
		crosslist=new JList();
		crosslist.setVisibleRowCount(10);
		crosslist.addListSelectionListener(this);
		crosslistPanel.add(new JScrollPane(crosslist),BorderLayout.CENTER);
		listPanel.add(crosslistPanel);

		attlistPanel=new JPanel();
		attlistPanel.setLayout(new GridLayout(2,1,5,5));
		listPanel.add(attlistPanel);
		
		JPanel fromattPanel=new JPanel();
		attlistPanel.add(fromattPanel);
		fromattPanel.setLayout(new BorderLayout());
		JPanel fromlabelPanel=new JPanel();
		fromlabelPanel.setLayout(new GridLayout(2,1,5,5));
		crossattlabel=new JLabel(Resource.getString("CROSSTABLE_SELECT_KEYS"));
		fromlabelPanel.add(crossattlabel);
		fromattlabel=new JLabel(Resource.getString("CROSSTABLE_FOREIGNKEYS")+" "+fromconcept.getName());
		fromlabelPanel.add(fromattlabel);
		fromattPanel.add(fromlabelPanel,BorderLayout.NORTH);
		fromattlist=new JList();
		fromattPanel.add(new JScrollPane(fromattlist),BorderLayout.CENTER);
		foreignKeyButton1=new JButton(Resource.getString("SELECT")+"...");		
		foreignKeyButton1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event){
				String table=(String) crosslist.getSelectedValue();
				table=table.substring(0,table.indexOf(" ("));

				DB m4DB=fromconcept.getConcept().getM4Db();
				String selectstring=m4DB.getSelectStringAllColumnsForDbObject(table);
				ResultSet resultset;
				Vector columns=new Vector();
				try {
					resultset = m4DB.executeBusinessSqlRead(selectstring);

					while (resultset.next()){
						columns.add(resultset.getString(1));						
					}
					resultset.close();

					Collections.sort(columns);

				} catch (DbConnectionClosed error) {
					M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				} catch (SQLException error) {
					M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				}
				
				String[] data=new String[columns.size()];
				for(int i=0;i<columns.size();i++){
					data[i]=(String) columns.get(i);					
				}
				
				ListModel model=fromattlist.getModel();
				String[] selected_data=new String[model.getSize()];
				for(int i=0;i<selected_data.length;i++){
					selected_data[i]=(String) model.getElementAt(i);
				}
				
				int min=fromlist.getModel().getSize();
				if (min==0){
					JOptionPane.showMessageDialog(app,Resource.getString("DIALOG_PRIMARYKEY_MESSAGE1")+fromconcept.getName()+Resource.getString("DIALOG_PRIMARYKEY_MESSAGE2"),
																	Resource.getString("DIALOG_PRIMARYKEY_TITLE"),JOptionPane.WARNING_MESSAGE);
					return;					
				}
				
				ListSelectDialog dialog=new ListSelectDialog(app,Resource.getString("DIALOG_FOREIGNKEY_TITLE"),Resource.getString("DIALOG_FOREIGNKEY_SUBTITLE"),data,selected_data,true,min,min);
				if (dialog.getExitAction()==ListSelectDialog.OK){
					selected_data=dialog.getSelectedDataItems();
					fromattlist.setListData(selected_data);
				}
			}
		});
		buttonPanel=new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(foreignKeyButton1);
		fromattPanel.add(buttonPanel,BorderLayout.SOUTH);

		JPanel toattPanel=new JPanel();
		attlistPanel.add(toattPanel);
		toattPanel.setLayout(new BorderLayout());
		toattlabel=new JLabel(Resource.getString("CROSSTABLE_FOREIGNKEYS")+" "+toconcept.getName());
		toattPanel.add(toattlabel,BorderLayout.NORTH);
		toattlist=new JList();
		toattPanel.add(new JScrollPane(toattlist),BorderLayout.CENTER);
		foreignKeyButton2=new JButton(Resource.getString("SELECT")+"...");		
		foreignKeyButton2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event){
				String table=(String) crosslist.getSelectedValue();
				table=table.substring(0,table.indexOf(" ("));

				DB m4DB=fromconcept.getConcept().getM4Db();
				String selectstring=m4DB.getSelectStringAllColumnsForDbObject(table);
				ResultSet resultset;
				Vector columns=new Vector();
				try {
					resultset = m4DB.executeBusinessSqlRead(selectstring);

					while (resultset.next()){
						columns.add(resultset.getString(1));						
					}
					resultset.close();

					Collections.sort(columns);

				} catch (DbConnectionClosed error) {
					M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				} catch (SQLException error) {
					M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				}
				
				String[] data=new String[columns.size()];
				for(int i=0;i<columns.size();i++){
					data[i]=(String) columns.get(i);					
				}
				
				ListModel model=toattlist.getModel();
				String[] selected_data=new String[model.getSize()];
				for(int i=0;i<selected_data.length;i++){
					selected_data[i]=(String) model.getElementAt(i);
				}
				
				int min=tolist.getModel().getSize();
				if (min==0){
					JOptionPane.showMessageDialog(app,Resource.getString("DIALOG_PRIMARYKEY_MESSAGE1")+toconcept.getName()+Resource.getString("DIALOG_PRIMARYKEY_MESSAGE2"),
																	Resource.getString("DIALOG_PRIMARYKEY_TITLE"),JOptionPane.WARNING_MESSAGE);
					return;
				}
				
				ListSelectDialog dialog=new ListSelectDialog(app,Resource.getString("DIALOG_FOREIGNKEY_TITLE"),Resource.getString("DIALOG_FOREIGNKEY_SUBTITLE"),data,selected_data,true,min,min);
				if (dialog.getExitAction()==ListSelectDialog.OK){
					selected_data=dialog.getSelectedDataItems();
					toattlist.setListData(selected_data);
				}			
			}
		});
		buttonPanel=new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(foreignKeyButton2);
		toattPanel.add(buttonPanel,BorderLayout.SOUTH);
		
		setOne2ManyType();
	}
	
	public void setOne2ManyType(){
		crosslist.setEnabled(false);
		crosslabel1.setEnabled(false);
		crosslabel2.setEnabled(false);
		fromlabel.setText(Resource.getString("FOREIGNKEYS")+":");	

		crosslist.clearSelection();
		valueChanged(null);
	}
	
	public void setMany2ManyType(){
		crosslist.setEnabled(true);
		crosslabel1.setEnabled(true);
		crosslabel2.setEnabled(true);
		fromattlist.setEnabled(false);
		toattlist.setEnabled(false);		
		fromlabel.setText(Resource.getString("PRIMARYKEYS")+":");	
		
		if (!tablesloaded){
			Vector colls=new Vector();
			try{
				colls.addAll(MiningMartApplication.m4Interface.getNamesOfBusinessTablesAndViews());
				Collections.sort(colls);
			}catch(M4Exception error){
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				colls=new Vector();
			}
			Iterator iter=colls.iterator();
			String[] tablenames=new String[colls.size()];
			int index=0;
			while (iter.hasNext()){
				tablenames[index]=(String) iter.next();
				try {
					if (MiningMartApplication.m4Interface.isBusinessTable(tablenames[index])){
						tablenames[index]+=" ("+Resource.getString("TABLE")+")";
					}else if (MiningMartApplication.m4Interface.isBusinessView(tablenames[index])){
						tablenames[index]+=" ("+Resource.getString("VIEW")+")";
					}else{
					}
				} catch (M4Exception error) {
					M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				}
				index++;
			}
			crosslist.setListData(tablenames);
			tablesloaded=true;
		}

	}

	/* (non-Javadoc)
	 * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
	 */
	public void valueChanged(ListSelectionEvent event) {
		if (crosslist.isSelectionEmpty()){
			foreignKeyButton1.setEnabled(false);
			foreignKeyButton2.setEnabled(false);
			fromattlist.setEnabled(false);
			toattlist.setEnabled(false);
			crossattlabel.setEnabled(false);
			fromattlabel.setEnabled(false);
			toattlabel.setEnabled(false);
			fromattlist.setListData(new Vector());
			toattlist.setListData(new Vector());
			tableselected=false;	
		}else{
			if (tableselected){
			}
			foreignKeyButton1.setEnabled(true);
			foreignKeyButton2.setEnabled(true);
			fromattlist.setEnabled(true);
			toattlist.setEnabled(true);	
			crossattlabel.setEnabled(true);
			fromattlabel.setEnabled(true);
			toattlabel.setEnabled(true);
			tableselected=true;	
		}
	}

	/**
	 * Fills the components if a relation is given.
	 */
	private boolean fillComponents(){
		
		 if (this.relation==null)
		 	return false;

		 boolean relationalLevelExists = true;
		 
		 nameField.setText(relation.getName());		 	
		 if (relation.isOneToManyRelation()){
			one2manyButton.setSelected(true);
			this.setOne2ManyType();
			ForeignKey fromKey;
			try {
				fromKey = relation.getFromKey();
			    if (fromKey == null) {
			    	relationalLevelExists = false;
			    	fromlist.setListData(new String [0]);
			    	tolist.setListData(new String[0]);
					return relationalLevelExists;	
			    }
				Collection fkLinks = fromKey.getAllColumnLinks();
				if (fkLinks.isEmpty()) {
					relationalLevelExists = false;			
				}
				
				//fill the from and to lists
				Iterator iter=fkLinks.iterator();
				String[] dataFrom=new String[fkLinks.size()];
				String[] dataTo = new String[fkLinks.size()];
				Column column;
				BaseAttribute baseatt;
				int index=0;
				while (iter.hasNext()){
					ForeignKeyLink link=(ForeignKeyLink) iter.next();
					column = link.getForeignKeyColumn();
					if (column == null) {
						relationalLevelExists = false;
					}
					else {
						baseatt=fromconcept.getConcept().getBaseAttribute(column);
						dataFrom[index]=baseatt.getName();
					}
					column = link.getPrimaryKeyColumn();
					if (column == null) {
						relationalLevelExists = false;
					}
					else {
						baseatt=toconcept.getConcept().getBaseAttribute(column);
						dataTo[index]=baseatt.getName();
					}
					index++;
				}
				fromlist.setListData(dataFrom);
				tolist.setListData(dataTo);

			} catch (M4Exception error) {
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
			}
		 	
		 }else{
			many2manyButton.setSelected(true);
			this.setMany2ManyType();
			try {
				Columnset colset=relation.getCrossLinkColumnSet();
				String tableName = colset.getName();
				try {
					if (MiningMartApplication.m4Interface.isBusinessTable(tableName)){
						tableName+=" ("+Resource.getString("TABLE")+")";
					}else if (MiningMartApplication.m4Interface.isBusinessView(tableName)){
						tableName+=" ("+Resource.getString("VIEW")+")";
					}else{
					}
				} catch (M4Exception error) {
					M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				}				
				crosslist.setSelectedValue(tableName,true);
				this.valueChanged(null);

				ForeignKey fromKey=relation.getFromKey();
				ForeignKey toKey=relation.getToKey();

				// iterate through the fromkey and fill the lists:
				Collection fkLinks = fromKey.getAllColumnLinks();
				if (fkLinks.isEmpty()) {
					throw new M4Exception("Found no links in the FromKey of this Relation!");
				}				
				Iterator iter=fkLinks.iterator();
				String[] dataFrom=new String[fkLinks.size()];
				String[] dataTo = new String[fkLinks.size()];
				Column column;
				BaseAttribute baseatt;
				int index=0;
				while (iter.hasNext()){
					ForeignKeyLink link=(ForeignKeyLink) iter.next();
					column = link.getForeignKeyColumn();
					dataFrom[index] = column.getName();
					column = link.getPrimaryKeyColumn();
					baseatt=fromconcept.getConcept().getBaseAttribute(column);
					dataTo[index]=baseatt.getName();
					index++;
				}
				fromlist.setListData(dataFrom);
				fromattlist.setListData(dataTo);
				
				// iterate through the tokey and fill the lists:
				fkLinks = toKey.getAllColumnLinks();
				if (fkLinks.isEmpty()) {
					throw new M4Exception("Found no links in the FromKey of this Relation!");
				}				
				iter=fkLinks.iterator();
				dataFrom=new String[fkLinks.size()];
				dataTo = new String[fkLinks.size()];
				index=0;
				while (iter.hasNext()){
					ForeignKeyLink link=(ForeignKeyLink) iter.next();
					column = link.getForeignKeyColumn();
					dataFrom[index]=column.getName();
					column = link.getPrimaryKeyColumn();
					baseatt=toconcept.getConcept().getBaseAttribute(column);
					dataTo[index]=baseatt.getName();
					index++;
				}
				tolist.setListData(dataFrom);
				toattlist.setListData(dataTo);

			} catch (M4Exception error) {
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
			}
		 }
		return relationalLevelExists;
	}
	
	private void createRelation(){
		
		// delete the old relation before creating the new
		if (this.relation!=null){
			try {
				this.relation.deleteSoon();
			} catch (M4Exception error) {
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
			}
		}

		Case currentcase=M4Interface.getCurrentCase();

		//get the name of the new relation
		String relName=nameField.getText();
		try {
			relName=currentcase.getValidName(relName,Relation.class);
		} catch (M4Exception error) {
			M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
		}
		nameField.setText(relName);

		// get the features of the fromconcept
		ListModel model=fromlist.getModel();
		Vector fromfeatures=new Vector();
		BaseAttribute baseatt=null;
		for(int i=0;i<model.getSize();i++){
			try {
				baseatt=fromconcept.getConcept().getBaseAttribute((String) model.getElementAt(i));
			} catch (M4Exception error) {
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				baseatt=null;
			}
			
			if (baseatt!=null){
				fromfeatures.add(baseatt);				
			}
			baseatt=null;
		}
		
		//get the features of the toconcept
		model=tolist.getModel();
		Vector tofeatures=new Vector();
		baseatt=null;
		for(int i=0;i<model.getSize();i++){
			try {
				baseatt=toconcept.getConcept().getBaseAttribute((String) model.getElementAt(i));
			} catch (M4Exception error) {
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				baseatt=null;
			}
			
			if (baseatt!=null){
				tofeatures.add(baseatt);				
			}
			baseatt=null;
		}


		if (one2manyButton.isSelected()){
			try {
				relation=currentcase.createOneToManyRelation(relName,fromfeatures, tofeatures);
			} catch (M4Exception error) {
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				JOptionPane.showMessageDialog(app,error.getMessage(),Resource.getString("DIALOG_ERROR_TITLE"),JOptionPane.ERROR_MESSAGE);
			}
		}else{

			String crosstable=(String) crosslist.getSelectedValue();
			crosstable=crosstable.substring(0,crosstable.indexOf(" ("));

			//get the foreignkeys of the crosstable referencing to the primary key of the fromconcept	
			Vector fromattcolumns=new Vector();
			model=fromattlist.getModel();
			for(int i=0;i<model.getSize();i++){
				fromattcolumns.add((String) model.getElementAt(i));
			}
			
			//get the foreignkeys of the crosstable referencing to the primary key of the toconcept	
			Vector toattcolumns=new Vector();
			model=toattlist.getModel();
			for(int i=0;i<model.getSize();i++){
				toattcolumns.add((String) model.getElementAt(i));
			}
			
			try {
				relation=currentcase.createManyToManyRelation(relName,fromfeatures,tofeatures,crosstable,fromattcolumns,toattcolumns);
			} catch (M4Exception error) {
				M4Interface.print.doPrint(Print.ERROR,error.getMessage(),error);
				JOptionPane.showMessageDialog(app,error.getMessage(),Resource.getString("DIALOG_ERROR_TITLE"),JOptionPane.ERROR_MESSAGE);
			}

		}
		
		if (this.mmartrelation!=null){
			this.mmartrelation.setRelation(relation);			
		}
	}
	
	public Relation getRelation(){
		return relation;
	}

	/**
	 * Called if one of the buttons was pressed.
	 */
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();

		if (cmd.equals(Resource.getString("CANCEL"))) {
			exitAction = CANCEL;
			this.dispose();
		}else if (cmd.equals(Resource.getString("OK"))) {
			exitAction = OK;
			createRelation();
			this.dispose();
		}

	}

	/**
	 *Gets the action when the dialog was exited.
	 */
	public int getExitAction() {
		return exitAction;
	}
	
	/**
	 * Returns the name of the <code>Relation</code>.
	 */
	public String getName(){
		return nameField.getText();		
	}
	

}
/*
 * Historie
 * --------
 *
 * $Log: CreateRelationDialog.java,v $
 * Revision 1.11  2006/04/11 14:10:16  euler
 * Updated license text.
 *
 * Revision 1.10  2006/04/06 16:31:16  euler
 * Prepended license remark.
 *
 * Revision 1.9  2006/03/24 13:14:58  euler
 * Bugfix
 *
 * Revision 1.8  2006/03/21 12:03:12  euler
 * Creating relations automatically works
 *
 * Revision 1.7  2006/03/20 16:44:22  euler
 * Bugfixes
 *
 * Revision 1.6  2006/01/25 11:30:23  euler
 * Bugfixes
 *
 * Revision 1.5  2006/01/12 13:20:10  euler
 * Bugfix
 *
 * Revision 1.4  2006/01/12 11:54:54  euler
 * Bugfix
 *
 * Revision 1.3  2006/01/12 09:31:45  hakenjos
 * Edit Relation...
 *
 * Revision 1.2  2006/01/06 16:23:30  euler
 * Small bugfix
 *
 * Revision 1.1  2006/01/03 09:54:25  hakenjos
 * Initial version!
 *
 */

/*
Revision 1.2  2005/12/15 09:15:55  hakenjos
*** empty log message ***

Revision 1.1  2005/12/13 09:32:34  hakenjos
Initial version!

 */
