package de.renew.navigator.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Arrays;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

import CH.ifa.draw.DrawPlugin;
import de.renew.draw.ui.api.ApplicationApi;
import de.renew.navigator.FilesystemController;
import de.renew.navigator.NavigatorAction;
import de.renew.navigator.gui.NavigatorIcons;


/**
 * @author Konstantin Simon Maria Moellers
 * @version 2015-08-26
 */
public class AddFilesAction extends NavigatorAction {
    /**
     * The {@link FilesystemController} instance that this action interacts with.
     */
    private final FilesystemController _fileSystemCtrl;

    /**
     * @param filesystemControl the filesystem controller
     */
    public AddFilesAction(FilesystemController filesystemControl) {
        super(
            "Add Files (Ctrl+Shift+O)", NavigatorIcons.ICON_ADD,
            KeyStroke.getKeyStroke("control shift O"));
        this._fileSystemCtrl = filesystemControl;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        DrawPlugin currentPlugin = DrawPlugin.getCurrent();
        if (currentPlugin != null) {
            // choose file or directory with JFileChooser
            JFileChooser fc = new JFileChooser(ApplicationApi.getLastPath());
            final FileFilter fileFilter = _fileSystemCtrl.getFileFilter();

            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fc.setAcceptAllFileFilterUsed(false);
            fc.addChoosableFileFilter(fileFilter);
            fc.setFileFilter(fileFilter);
            fc.setFileHidingEnabled(true);
            fc.setMultiSelectionEnabled(true);
            int returnVal = fc.showOpenDialog(null);

            // File chooser was not approved?
            if (returnVal != JFileChooser.APPROVE_OPTION) {
                return;
            }

            File[] files = fc.getSelectedFiles();

            // Loads root directories
            _fileSystemCtrl.loadRootDirectories(Arrays.asList(files));

            File parent = files[0].getParentFile();
            if (parent != null && parent.isDirectory()) {
                currentPlugin.getIOHelper().setLastPath(parent);
            }
        }
    }
}