/*
 * File:     AbstractExportDialog.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.export;

import mpi.eudico.client.annotator.Constants;
import mpi.eudico.client.annotator.ElanLocale;
import mpi.eudico.client.annotator.Preferences;

import mpi.eudico.client.util.DefaultFileFilter;
import mpi.eudico.client.util.ExportException;

import java.awt.*;
import java.awt.event.*;

import java.io.File;
import java.io.IOException;

import javax.swing.*;
import javax.swing.border.*;


/**
 * Created on Apr 15, 2004
 * @author Alexander Klassmann
 * @version Apr 15, 2004
 */
public abstract class AbstractExportDialog extends JDialog {
    final protected JList tierList;
    final protected JLabel titleLabel;
    final protected JCheckBox restrictCheckBox;
    protected String fileExtension = "";
    protected String fileDescription = "*";
    final private JButton exportFileButton;
    private File exportFile;

    /**
     *
     * @see java.awt.Dialog#Dialog(Frame, boolean)
     */
    public AbstractExportDialog(Frame frame, boolean modal) {
        super(frame, modal);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        titleLabel = new JLabel();
        titleLabel.setFont(titleLabel.getFont().deriveFont(16f));
        titleLabel.setBorder(new EmptyBorder(10, 10, 10, 10));

        JLabel selectLabel = new JLabel(ElanLocale.getString("Button.Select") +
                " tier: ");
        selectLabel.setBorder(new EmptyBorder(0, 5, 0, 5));

        tierList = new JList();
        tierList.setBackground(Constants.DEFAULTBACKGROUNDCOLOR);
        tierList.setForeground(Constants.DEFAULTFOREGROUNDCOLOR);
        tierList.setSelectionBackground(Constants.SELECTIONCOLOR);

        JLabel restrictLabel = new JLabel(ElanLocale.getString(
                    "ExportDialog.Restrict") + " :");
        restrictCheckBox = new JCheckBox();

        JLabel exportLabel = new JLabel(ElanLocale.getString(
                    "ExportDialog.ExportToFile") + " :");
        exportLabel.setBorder(new EmptyBorder(5, 5, 5, 5));

        Action chooseFileAction = new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    File newFile = showChooser(exportFile);

                    if (newFile != null) {
                        setExportFile(newFile);
                    }
                }
            };

        exportFileButton = new JButton(chooseFileAction);

        JPanel buttonPanel = new JPanel(new GridLayout());
        Action exportAction = new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    if ((exportFile != null) && exportFile.exists()) {
                        int option = JOptionPane.showConfirmDialog(AbstractExportDialog.this,
                                ElanLocale.getString("Message.Overwrite"),
                                ElanLocale.getString("Menu.File.Export"),
                                JOptionPane.YES_NO_OPTION);

                        if (option != JOptionPane.YES_OPTION) {
                            return;
                        }
                    }

                    try {
                        export(exportFile);
                        dispose();
                    } catch (ExportException ex) {
                        JOptionPane.showMessageDialog(AbstractExportDialog.this,
                            ElanLocale.getString(ex.getMessage()),
                            ElanLocale.getString("Message.Error"),
                            JOptionPane.ERROR_MESSAGE);
                    } catch (Exception ex) {
                        // display IOexception if writing to file fails
                        StringBuffer message = new StringBuffer(ElanLocale.getString(
                                    "ExportDialog.Message.Error"));
                        message.append("\n");
                        message.append(ex.getMessage());
                        JOptionPane.showMessageDialog(AbstractExportDialog.this,
                            message.toString(),
                            ElanLocale.getString("Message.Error"),
                            JOptionPane.ERROR_MESSAGE);
                    }
                }
            };

        JButton exportButton = new JButton(exportAction);
        exportButton.setText(ElanLocale.getString("Button.OK"));

        Action cancelAction = new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                }
            };

        JButton cancelButton = new JButton(cancelAction);
        cancelButton.setText(ElanLocale.getString("Button.Cancel"));
        buttonPanel.add(exportButton);
        buttonPanel.add(cancelButton);

        c.insets = new Insets(5, 5, 5, 5);
        c.gridwidth = GridBagConstraints.REMAINDER;
        panel.add(titleLabel, c);
        c.anchor = GridBagConstraints.NORTHEAST;
        c.gridwidth = GridBagConstraints.RELATIVE;
        panel.add(selectLabel, c);
        c.anchor = GridBagConstraints.WEST;
        c.gridwidth = GridBagConstraints.REMAINDER;
        panel.add(tierList, c);
        c.anchor = GridBagConstraints.EAST;
        c.gridwidth = GridBagConstraints.RELATIVE;
        panel.add(restrictLabel, c);
        c.anchor = GridBagConstraints.WEST;
        c.gridwidth = GridBagConstraints.REMAINDER;
        panel.add(restrictCheckBox, c);
        c.anchor = GridBagConstraints.EAST;
        c.gridwidth = GridBagConstraints.RELATIVE;
        panel.add(exportLabel, c);
        c.anchor = GridBagConstraints.WEST;
        c.gridwidth = GridBagConstraints.REMAINDER;
        panel.add(exportFileButton, c);
        c.anchor = GridBagConstraints.CENTER;
        panel.add(buttonPanel, c);

        getContentPane().add(panel);

        addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    dispose();
                }
            });
    }

    /**
     *
     * @param exportFile
     * @throws Exception
     */
    abstract protected void export(File exportFile) throws Exception;

    /**
     *
     * @param file
     */
    protected void setExportFile(File file) {
        this.exportFile = file;
        exportFileButton.setText(exportFile.getAbsolutePath());
    }

    /**
     *
     * @param defaultFile
     * @return File
     */
    protected File showChooser(File defaultFile) {
        JFileChooser chooser = new JFileChooser();
        chooser.setSelectedFile(defaultFile);
        chooser.setDialogTitle(ElanLocale.getString(
                "ExportDialog.FileChooser.Title"));

        File exportFile = null;

        DefaultFileFilter filter = new DefaultFileFilter(fileExtension,
                fileDescription);

        chooser.setFileFilter(filter);

        if (chooser.showDialog(this, ElanLocale.getString("Button.Select")) == JFileChooser.APPROVE_OPTION) {
            File curDir = chooser.getCurrentDirectory();

            if (curDir != null) {
                Preferences.set("LastUsedExportDir", curDir.getAbsolutePath(),
                    null);
            }

            exportFile = chooser.getSelectedFile();

            if (exportFile != null) {
                String name = exportFile.getAbsolutePath();

                if (!name.toLowerCase().endsWith(fileExtension)) {
                    name += fileExtension;
                    exportFile = new File(name);
                }
            }
        }

        return exportFile;
    }
}
