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

import be.iminds.ilabt.jfed.experimenter_gui.slice.ExperimentViewController;
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 be.iminds.ilabt.jfed.rspec.rspec_source.RequestRspecSource;
import javafx.concurrent.Task;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * User: twalcari
 * Date: 2/2/2015
 * Time: 16:44
 */
public class SaveExperimentDescriptionAction extends ExperimentViewAction {
    private static final Logger LOG = LoggerFactory.getLogger(SaveExperimentDescriptionAction.class);


    private final TaskService taskService;
    private final JFedPreferences jFedPreferences;

    SaveExperimentDescriptionAction(Window parentWindow, ExperimentViewController experimentViewController, TaskService taskService, JFedPreferences jFedPreferences) {
        super(experimentViewController);
        this.taskService = taskService;
        this.jFedPreferences = jFedPreferences;
    }

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


        if (jFedPreferences.containsPreference(GuiPreferenceKey.PREF_RSPECFOLDER_REQUEST))
            fc.setInitialDirectory(new File(jFedPreferences.getString(GuiPreferenceKey.PREF_RSPECFOLDER_REQUEST)));
        else if (System.getProperty("user.home") != null)
            fc.setInitialDirectory(new File(System.getProperty("user.home")));

        File file = fc.showSaveDialog(parentWindow);

        if (file == null)
            return;


        //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);

        Task<Void> saveTask = createSaveExperimentDefinitionTask(file);
        taskService.submitTask(saveTask);
    }

    private Task<Void> createSaveExperimentDefinitionTask(File file) {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                updateMessage(String.format("Writing experiment definition to '%s'", file.getAbsolutePath()));


                try (FileWriter writer = new FileWriter(file)) {
                    RequestRspecSource rrs =
                            new RequestRspecSource(experimentViewController.getTimelineView().getModelRspec());
                    writer.write(rrs.getRspecXmlString());//getNewRequestRspecSource().getRspecXmlString());
                    writer.flush();
                    writer.close();
                    updateMessage(String.format("Wrote experiment definition to '%s'", file.getAbsolutePath()));

                } catch (IOException ex) {
                    LOG.error("Error while writing experiment description", ex);
                    updateMessage("Error while writing experiment description");
                }

                return null;
            }
        };
    }
}
