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

import be.iminds.ilabt.jfed.highlevel.jobs.RegisterExperimentJob;
import be.iminds.ilabt.jfed.highlevel.jobs.StateFinishedListener;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.ilabt.jfed.ui.javafx.dialogs.JFDialogs;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: twalcari
 * Date: 12/1/2015
 * Time: 17:25
 */
public class RegisterExperimentStateListener implements StateFinishedListener<RegisterExperimentJob.ExecuteTaskState> {
    private static final Logger LOG = LoggerFactory.getLogger(RegisterExperimentStateListener.class);

    @Override
    public void onStateFinished(RegisterExperimentJob.ExecuteTaskState state) {
        if (state.getTask().getSlice() == null) {
            LOG.error("Create Slice task failed. (createSliceTask.getSlice() == null)");

            //check if it is a duplicate slice name error
            boolean isDuplicateSliceError = false;

            if (state.getTaskExecution().getException() instanceof JFedException) {     //exception == null will return false
                JFedException ex = (JFedException) state.getTaskExecution().getException();

                if (ex.getXmlRpcReply() != null && ex.getXmlRpcReply().getOutput() != null &&
                        ex.getXmlRpcReply().getOutput().endsWith(" already a registered slice")) {
                    isDuplicateSliceError = true;
                    LOG.warn("Detected that exception of register experiment is a duplicate slice error");
                } else {
                    LOG.warn("Received an unrecognized other error: {}",
                            ex.getXmlRpcReply() != null ? ex.getXmlRpcReply().getOutput() : "null");
                }
            }

            if (isDuplicateSliceError) {

                Platform.runLater(() -> JFDialogs.create()
                        .message("The experiment name that you requested is already in use on the slice authority. Please try again with another name.\n\n" +
                                "Check the Errors-tab for more information.")
                        .masthead("Experiment name already in use")
                        .title("Experiment registration failed")
                        .showError());
            } else {

                Platform.runLater(() -> JFDialogs.create()
                        .message("An error occurred when requesting the slice credential.\n\n." +
                                "Check the Errors-tab for more information.")
                        .masthead("Experiment registration failed")
                        .title("Experiment registration failed")
                        .showError());

            }
        }
    }
}
