package hirondelle.stocks.export;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.util.logging.*;
import hirondelle.stocks.portfolio.PortfolioDAO;
import hirondelle.stocks.util.Args;
import hirondelle.stocks.util.ui.UiUtil;
import hirondelle.stocks.util.Util;
public final class ImportAction extends AbstractAction {
public ImportAction(JFrame aFrame) {
super("Import...", UiUtil.getEmptyIcon());
Args.checkForNull(aFrame);
fFrame = aFrame;
putValue(SHORT_DESCRIPTION, "Import the result of a previous Export operation.");
putValue(
LONG_DESCRIPTION, "Replace all Portfolios with those defined in a text file."
);
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_I) );
}
@Override public void actionPerformed (ActionEvent event) {
fLogger.info("Importing portfolios from a text file.");
JFileChooser chooser = new JFileChooser(fDirOfInterest);
chooser.setDialogTitle("Import-Replace All Portfolios");
chooser.setApproveButtonToolTipText("Replace all Portfolios");
int choice = chooser.showDialog(fFrame, "Import-And-Replace");
if (choice != JFileChooser.APPROVE_OPTION) {
fLogger.fine("No file selection made");
return;
}
File file = chooser.getSelectedFile();
fDirOfInterest = file.getParentFile();
if ( !file.exists() ){
fLogger.fine("Selected file does not exist " + file);
showErrorMessage(fNOT_EXIST_MESSAGE);
return;
}
if ( file.exists() && !file.canRead() ){
fLogger.fine("File does not have read access: " + file);
showErrorMessage(fNO_READ_MESSAGE);
return;
}
fLogger.fine("Attempting to import file");
PortfolioDAO dao = new PortfolioDAO();
dao.importXML(file);
}
private JFrame fFrame;
private static File fDirOfInterest;
private static final String fINVALID_IMPORT_FILE = "Invalid Import File";
private static final Object[] fNO_READ_MESSAGE = {
"File cannot be read.",
"A readable file must be selected for an Import.",
"Please select a different file."
};
private static final Object[] fNOT_EXIST_MESSAGE = {
"File does not currently exist.",
"An existing file must be selected for an Import.",
"Please select a different file."
};
private static final Logger fLogger = Util.getLogger(ImportAction.class);
private void showErrorMessage(Object[] aMessage){
JOptionPane.showMessageDialog(
fFrame, aMessage,
UiUtil.getDialogTitle(fINVALID_IMPORT_FILE),
JOptionPane.ERROR_MESSAGE
);
}
}