package be.iminds.ilabt.jfed.experimenter_gui.editor.actions;

import be.iminds.ilabt.jfed.experimenter_gui.editor.EditableRspec;
import be.iminds.ilabt.jfed.experimenter_gui.editor.tasks.SaveRspecTask;
import be.iminds.ilabt.jfed.experimenter_gui.ui.progressbar.TaskService;
import be.iminds.ilabt.jfed.experimenter_gui.util.FileUtils;
import be.iminds.ilabt.jfed.preferences.GuiPreferenceKey;
import be.iminds.ilabt.jfed.preferences.JFedPreferences;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * User: twalcari
 * Date: 5/20/2015
 * Time: 09:14
 */
public class SaveRspecAction extends EditorAction<Boolean> {
    private static final Logger LOG = LoggerFactory.getLogger(SaveRspecAction.class);

    private final TaskService taskService;
    private final JFedPreferences jFedPreferences;

    SaveRspecAction(EditableRspec editableRspec, Window parentWindow,
                    TaskService taskService, JFedPreferences jFedPreferences) {
        super(editableRspec, parentWindow);
        this.taskService = taskService;
        this.jFedPreferences = jFedPreferences;
    }

    @Override
    public Boolean call() {
        FileChooser fc = new FileChooser();
        fc.setTitle("Save experiment");
        fc.getExtensionFilters().add(FileUtils.RSPEC_EXTENSION_FILTER);
        fc.setInitialFileName(editableRspec.getName() + FileUtils.EXPERIMENT_FILE_EXTENSION);


        //set the default save dir
        if (System.getProperty("user.home") != null)
            fc.setInitialDirectory(new File(System.getProperty("user.home")));

        if (jFedPreferences.containsPreference(GuiPreferenceKey.PREF_RSPECFOLDER_REQUEST)) {
            File dir = new File(jFedPreferences.getString(GuiPreferenceKey.PREF_RSPECFOLDER_REQUEST));
            if (dir.exists()) {
                fc.setInitialDirectory(dir);
            }
        }

        if (editableRspec.getFile() != null) {
            fc.setInitialDirectory(editableRspec.getFile().getParentFile());
            fc.setInitialFileName(editableRspec.getFile().getName());
        }

        File file = fc.showSaveDialog(parentWindow);

        if (file == null)
            return false;


        //save folder in which the file was saved for future file selector dialogs
        jFedPreferences.setString(GuiPreferenceKey.PREF_RSPECFOLDER_REQUEST,
                file.getParentFile().getAbsolutePath());

        if (!file.getAbsolutePath().endsWith(FileUtils.EXPERIMENT_FILE_EXTENSION))
            file = new File(file.getAbsolutePath() + FileUtils.EXPERIMENT_FILE_EXTENSION);


        editableRspec.setName(file.getName().substring(0, file.getName().length() - FileUtils.EXPERIMENT_FILE_EXTENSION.length()));

        taskService.submitTask(new SaveRspecTask(editableRspec.getRequestRspecSource(), file));

        editableRspec.setFile(file);

        return true;
    }


}
