package be.iminds.ilabt.jfed.highlevel.jobs;

import be.iminds.ilabt.jfed.experiment.Experiment;
import be.iminds.ilabt.jfed.experiment.ExperimentState;
import be.iminds.ilabt.jfed.highlevel.controller.TaskExecution;
import be.iminds.ilabt.jfed.highlevel.controller.TaskThread;
import be.iminds.ilabt.jfed.highlevel.tasks.CreateSliceTask;
import be.iminds.ilabt.jfed.highlevel.tasks.HighLevelTaskFactory;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: twalcari
 * Date: 12/1/2015
 * Time: 17:20
 */
public class RegisterExperimentJob extends SingleTaskJob<CreateSliceTask, Void> {
    private static final Logger LOG = LoggerFactory.getLogger(RegisterExperimentJob.class);

    public RegisterExperimentJob(Experiment experiment, HighLevelTaskFactory hltf, TaskThread tt) {
        super("Register experiment " + experiment.getName(), experiment, hltf, tt);
    }

    @Override
    public CreateSliceTask createTask() {
        assert experiment.getName() != null;
        assert (experiment.getSlice() == null);
        assert (experiment.getRequestedEndTime() != null);

        return hltf.createSlice(experiment.getName(), experiment.getSubAuthName(), experiment.getRequestedEndTime());
    }


    @Override
    protected void onFinished(CreateSliceTask task, TaskExecution<CreateSliceTask> taskExecution) {
        if (task.getSlice() == null && taskExecution.getException() instanceof JFedException) {
            //exception == null will return false
            JFedException ex = (JFedException) taskExecution.getException();
            if (ex.getXmlRpcReply() != null && ex.getXmlRpcReply().getOutput() != null &&
                    ex.getXmlRpcReply().getOutput().endsWith(" already a registered slice")) {
                LOG.warn("Detected that exception of register experiment is a duplicate slice error");

                updateMessage("Experiment name already in use. Restart the experiment with another name...");

            }

            Platform.runLater(() -> {
                //an error occurred, stop the process!
                LOG.debug("Failed to register experiment -> setting experiment status to FAILED");
                experiment.setExperimentState(ExperimentState.FAILED);
            });
        } else
            Platform.runLater(() -> {
                if (task.getSlice() == null ||
                        task.getSlice().getUrn() == null ||
                        taskExecution.getState() != TaskExecution.TaskState.SUCCESS) {
                    LOG.error("Something when wrong with the CreateSliceTask -> setting experiment status to FAILED");
                    experiment.setExperimentState(ExperimentState.FAILED);
                } else {
                    experiment.registerSlice(task.getSlice());
                    experiment.setExperimentState(ExperimentState.CREATED);
                }
            });
    }
}
