/*
 * Created on 30-03-2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package net.sf.hibern8ide;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import net.sf.hibern8ide.swing.*;

/**
 * @author max
 *
 */
public class ConfigurationUI extends JPanel {

    interface ConfigurationUIListener {
        
        public void configurationChanged(File xmlconfig, Properties properties, List mappingFiles);
        
    }
    
    ConfigurationUIListener listener = null;
    
   
    JFileChooser chooser = new JFileChooser(new File(".").getAbsolutePath());


    JTextField configField;
    DefaultListModel mappings = new DefaultListModel();

    JTextField propertyFileField;
       
    private JList mappingsList;

    ConfigurationUI(ConfigurationUIListener cul) {
        super();
        listener = cul;
        setupUI();
    }

    void setupUI() {

        // Create a TableLayout for the frame
        double border = 4;
        double size[][] =
            {
                {
                    border,
                    TableLayout.MINIMUM,
                    TableLayout.FILL,
                    TableLayout.MINIMUM,
                    border },
            // Columns
            {
                border,
                    TableLayout.MINIMUM,
                    TableLayout.MINIMUM,
                    TableLayout.FILL,
                    TableLayout.MINIMUM,
                    border }
        }; // Rows

        setLayout(new TableLayout(size));
       
        this.add(new JLabel("Properties:"), "1, 1");
        propertyFileField = new JTextField();
        this.add(propertyFileField, "2, 1");
        this.add(new JButton(new OpenProperties("...", "properties", "Property files", propertyFileField)), "3, 1");

        this.add(new JLabel("Config file:"), "1, 2");
        configField = new JTextField();
        this.add(configField, "2, 2");
        this.add(new JButton(new OpenProperties("...", "xml", "Hibernate cfg.xml files", configField)), "3, 2");

        mappingsList = new JList();
        mappingsList.setModel(mappings);
        this.add(new JScrollPane(mappingsList), "1, 3, 2, 3");

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.Y_AXIS));
        buttonPanel.add(new JButton(new AddHbmXML("Add...")));
        buttonPanel.add(new JButton(new RemoveHbmXml("Remove")));
        buttonPanel.add(new JButton(new MoveHbmXml("Up", true)));
        buttonPanel.add(new JButton(new MoveHbmXml("Down", false)));
        buttonPanel.add(new JButton(new ApplyConfig()));

        this.add(buttonPanel, "3,3, c, c");

    }

    /* (non-Javadoc)
     * @see javax.swing.JComponent#getMinimumSize()
     */
    public Dimension getMinimumSize() {

        return new Dimension(200, 100);
    }

    public class AddHbmXML extends AbstractAction {
        AddHbmXML() {
            super("Add hbm.xml");
        }
        public AddHbmXML(String string) {
            super(string);
        }
        public void actionPerformed(ActionEvent e) {
            chooser.resetChoosableFileFilters();
            chooser.addChoosableFileFilter(
                new SimpleFileFilter("xml", "Hibnerate mapping"));

            chooser.setMultiSelectionEnabled(true);
            int returnVal =
                chooser.showOpenDialog(
                    SwingUtilities.getWindowAncestor(ConfigurationUI.this));
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File[] files = chooser.getSelectedFiles();
                for (int i = 0; i < files.length; i++) {
                    mappings.addElement(files[i]);
                }
            }

        }
    }

    public class OpenProperties extends AbstractAction {
        
        private JTextField field;
        private String prefixName;
        private String prefix;
        
        public OpenProperties(String string, String prefix, String name, JTextField field) {
            super(string);
            this.prefix = prefix;
            this.prefixName = name;
            this.field = field;    
        }
        public void actionPerformed(ActionEvent e) {
            chooser.setMultiSelectionEnabled(true);
            chooser.resetChoosableFileFilters();
            SimpleFileFilter sff = new SimpleFileFilter(prefix, prefixName);
            chooser.addChoosableFileFilter(sff);
            int returnVal =
                chooser.showOpenDialog(
                    SwingUtilities.getWindowAncestor(ConfigurationUI.this));
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                field.setText(chooser.getSelectedFile().toString());
            }
        }
    }

    public class RemoveHbmXml extends AbstractAction {
        RemoveHbmXml(String str) {
            super(str);
        }

        /* (non-Javadoc)
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {
            mappings.remove(mappingsList.getSelectedIndex());
        }
    }

    public class MoveHbmXml extends AbstractAction {
        boolean up;
        MoveHbmXml(String str, boolean up) {

            super(str);
            this.up = up;
        }

        public void actionPerformed(ActionEvent e) {
            int si = mappingsList.getSelectedIndex();
            if (up && si > 0) {
                Object object = mappings.remove(si);
                mappings.add(si - 1, object);
                mappingsList.setSelectedIndex(si-1);
            } else if (!up && si < mappings.size()-1) {
                Object object = mappings.remove(si);
                mappings.add(si + 1, object);
                mappingsList.setSelectedIndex(si+1);
            }

        }
    }
    /**
        * @author max
        *
        */
       public class ApplyConfig extends AbstractAction {

           
        ApplyConfig() {
               super("Apply");
           }
           public void actionPerformed(ActionEvent e) {
               
                          if (listener!=null) {
                              List l = new ArrayList();
                              for(int i = 0; i<mappings.getSize(); i++) {
                                  l.add(mappings.get(i));
                              }
                              
                              Properties props = new Properties();
                              
                              if(propertyFileField.getText()!=null) {
                                try {
                                   props.load(new FileInputStream(propertyFileField.getText()));
                                } catch (FileNotFoundException e1) {
                                   e1.printStackTrace();
                                } catch (IOException e1) {
                                   e1.printStackTrace();
                                }
                              }
                              
                              String cfg = configField.getText();
                              File cfgFile = null;
                              if(cfg.trim().length()!=0) {
                                  cfgFile = new File(cfg); 
                              }
                               
                              listener.configurationChanged(cfgFile, props, l);                              
                          }
           }

       }
}
