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


import be.iminds.ilabt.jfed.rspec.rspec_source.RequestRspecSource;
import be.iminds.ilabt.jfed.ui.javafx.dialogs.JFDialogs;
import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * User: twalcari
 * Date: 5/20/2015
 * Time: 09:35
 */
public class SaveRspecTask extends Task<Void> {
    private static final Logger LOG = LoggerFactory.getLogger(SaveRspecTask.class);


    private final RequestRspecSource requestRspecSource;
    private final File saveFile;

    public SaveRspecTask(RequestRspecSource requestRspecSource, File saveFile) {
        this.requestRspecSource = requestRspecSource;
        this.saveFile = saveFile;

        updateTitle("Saving manifest to \"" + saveFile.getAbsolutePath() + "\"");
    }

    @Override
    protected Void call() throws Exception {
        FileWriter writer = new FileWriter(saveFile);
        writer.write(requestRspecSource.getRspecXmlString());
        writer.flush();
        writer.close();

        updateMessage("Successfully saved experiment in \"" + saveFile.getAbsolutePath() + "\"");

        return null;
    }

    @Override
    protected void failed() {
        LOG.error("Error while saving experiment to file '" + saveFile.getAbsolutePath() + "'", getException());

        JFDialogs.create()
                .message("An error occurred while saving the rspec.")
                .masthead("Error")
                .title("Error")
                .showException(getException());

    }


}
