/*
 * File:     TextExportFileChooser.java
 * Project:  MPI Linguistic Application
 * Date:     03 April 2006
 *
 * Copyright (C) 2001-2006  Max Planck Institute for Psycholinguistics
 *
 * 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; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package mpi.eudico.client.annotator.gui;

import mpi.eudico.client.annotator.ElanLocale;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import java.io.File;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;


/**
 * A custom save dialog that adds a combo box to select an encoding for  the
 * text file.
 *
 * @author Han Sloetjes
 * @version 1.0 sep 2005
 */
public class TextExportFileChooser extends JComponent implements ActionListener {
    private JFileChooser chooser;
    private JButton okButton;
    private JButton cancelButton;
    private String dialogTitle;
    private JDialog dialog;
    private int returnValue = JFileChooser.ERROR_OPTION;
    private JLabel encLabel;
    private JComboBox encodingBox;

    /**
     * Creates a new TextExportFileChooser instance
     */
    public TextExportFileChooser() {
        initComponents();
    }

    /**
     * Sets up the components. The standard "Save" and "Cancel" buttons  are
     * replaced because of layout considerations (the encoding combobox  is
     * best situated above the control buttons).
     */
    private void initComponents() {
        encLabel = new JLabel("Encoding: ");
        encodingBox = new JComboBox();
        encodingBox.addItem("ISO-LATIN");
        encodingBox.addItem("UTF-8");
        encodingBox.addItem("UTF-16");
        encodingBox.setSelectedIndex(1);
        okButton = new JButton();
        cancelButton = new JButton();

        this.setLayout(new GridBagLayout());

        Insets insets = new Insets(0, 6, 6, 6);
        chooser = new JFileChooser();
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);

        chooser.setControlButtonsAreShown(false);

        //chooser.addActionListener(this);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        this.add(chooser, gbc);

        JPanel encPanel = new JPanel();
        encPanel.add(encLabel);
        encPanel.add(encodingBox);

        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.SOUTH;
        gbc.fill = GridBagConstraints.NONE;
        gbc.insets = insets;
        this.add(encPanel, gbc);

        JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 6, 6));
        okButton.setText(ElanLocale.getString("Menu.File.Save"));
        okButton.addActionListener(this);
        cancelButton.setText(ElanLocale.getString("Button.Cancel"));
        cancelButton.addActionListener(this);

        if (System.getProperty("os.name").startsWith("Mac OS X")) {
            buttonPanel.add(cancelButton);
            buttonPanel.add(okButton);
        } else {
            buttonPanel.add(okButton);
            buttonPanel.add(cancelButton);
        }

        JPanel butBorderPanel = new JPanel(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        butBorderPanel.add(new JPanel(), gbc);
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.insets = insets;
        butBorderPanel.add(buttonPanel, gbc);

        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.anchor = GridBagConstraints.SOUTH;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = insets;
        this.add(butBorderPanel, gbc);
    }

    /**
     * Copied from JFileChooser.
     *
     * @param parent the parent component, usually a frame
     * @param approveButtonText the text for the "OK" or approve button
     *
     * @return JFileChooser.ERROR_OPTION, APPROVE_OPTION or CANCEL_OPTION
     *
     * @throws HeadlessException
     *
     * @see JFileChooser.showDialog(Component, String)
     */
    public int showSaveDialog(Component parent, String approveButtonText)
        throws HeadlessException {
        if (approveButtonText != null) {
            chooser.setApproveButtonText(approveButtonText);
        }

        dialog = createDialog(parent);
        dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    returnValue = JFileChooser.CANCEL_OPTION;
                }
            });
        returnValue = JFileChooser.ERROR_OPTION;

        dialog.show(); // blocks...

        dialog.dispose();
        dialog = null;

        return returnValue;
    }

    /**
     * Copied from JFileChooser. Creates a configured dialog.
     *
     * @param parent the parent
     *
     * @return a dialog object
     *
     * @throws HeadlessException
     */
    protected JDialog createDialog(Component parent) throws HeadlessException {
        Frame frame = (parent instanceof Frame) ? (Frame) parent
                                                : (Frame) SwingUtilities.getAncestorOfClass(Frame.class,
                parent);

        JDialog dialog = new JDialog(frame, dialogTitle, true);

        Container contentPane = dialog.getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(this, BorderLayout.CENTER);

        dialog.pack();
        dialog.setLocationRelativeTo(parent);

        return dialog;
    }

    /**
     * Returns the selected character encoding.
     *
     * @return the selected character encoding, default is UTF-8
     */
    public String getSelectedEncoding() {
        String enc = (String) encodingBox.getSelectedItem();

        if (enc == null) {
            enc = "UTF-8";
        } else if (enc.equals("ISO-LATIN")) {
            enc = "ISO-8859-1";
        }

        return enc;
    }

    /**
     * Selects the specified encoding in the encoding combo box.
     *
     * @param encoding the encoding to select
     */
    public void setSelectedEncoding(String encoding) {
        encodingBox.setSelectedItem(encoding);
    }

    /**
     * Returns the current directory.
     *
     * @return the current directory
     */
    public File getCurrentDirectory() {
        return chooser.getCurrentDirectory();
    }

    /**
     * Sets the directory for the chooser.
     *
     * @param dir the directory for the chooser
     */
    public void setCurrentDirectory(File dir) {
        chooser.setCurrentDirectory(dir);
    }

    /**
     * Returns the selected File.
     *
     * @return the selected File
     */
    public File getSelectedFile() {
        return chooser.getSelectedFile();
    }

    /**
     * Sets the file filter.
     *
     * @param filter the file filter for the chooser
     */
    public void setFileFilter(FileFilter filter) {
        chooser.setFileFilter(filter);
    }

    /**
     * Returns the current file filter
     *
     * @return the current file filter
     */
    public FileFilter getFileFilter() {
        return chooser.getFileFilter();
    }

    /**
     * Sets the title for the dialog.
     *
     * @param title the title
     */
    public void setDialogTitle(String title) {
        dialogTitle = title;

        if (dialog != null) {
            dialog.setTitle(title);
        }
    }

    /**
     * Action Listener implementation.
     *
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == okButton) {
            // method approveSelection() does not seem to set the file name typed in 
            // the textfield as the selected file
            // chooser.approveSelection();
            // find the first textfield encountered
            Component c = getTextField(chooser);

            if (c instanceof JTextField) {
                String fileName = ((JTextField) c).getText();
                chooser.setSelectedFile(new File(
                        chooser.getCurrentDirectory(), fileName));
            }

            returnValue = JFileChooser.APPROVE_OPTION;
            dialog.setVisible(false);
        } else if (e.getSource() == cancelButton) {
            returnValue = JFileChooser.CANCEL_OPTION;
            dialog.setVisible(false);
        }
    }

    /**
     * Recursively test all child components untill a TexrtField is
     * encountered.
     *
     * @param container the container holding child components
     *
     * @return the first JTextField or null
     */
    private Component getTextField(Container container) {
        Component c = null;

        if (container != null) {
            Component[] cc = container.getComponents();

            for (int i = 0; i < cc.length; i++) {
                c = cc[i];

                //System.out.println("C: " + c.getClass());
                if (c instanceof JTextField) {
                    return c;
                } else if (c instanceof Container) {
                    c = getTextField((Container) c);

                    if (c instanceof JTextField) {
                        return c;
                    }
                }
            }
        }

        return c;
    }
}
