package be.iminds.jfed.gts_highlevel.jobs.gts_parts;

import be.iminds.ilabt.jfed.experiment.tasks.ExperimentTaskStatus;
import be.iminds.ilabt.jfed.highlevel.jobs.ExperimentPartStateSlice;
import be.iminds.ilabt.jfed.highlevel.jobs.Job;
import be.iminds.ilabt.jfed.highlevel.jobs.SingleCallState;
import be.iminds.ilabt.jfed.highlevel.model.InternalState;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.jfed.gts_highlevel.model.GtsXmlProject;
import be.iminds.jfed.gts_highlevel.tasks.GtsTaskFactory;
import be.iminds.jfed.gts_highlevel.tasks.StopGtsResourcesTask;

/**
 * User: twalcari
 * Date: 1/18/2016
 * Time: 14:43
 */
public class StopGtsExperimentPartStateSlice extends ExperimentPartStateSlice<GtsExperimentPart> {
    private final GtsTaskFactory gtsTaskFactory;

    public StopGtsExperimentPartStateSlice(Job<?> job, GtsExperimentPart experimentPart, GtsTaskFactory gtsTaskFactory) {
        super(job, experimentPart);
        this.gtsTaskFactory = gtsTaskFactory;
    }

    @Override
    public ExperimentTaskStatus statefulRun() throws JFedException, InterruptedException {
        GtsXmlProject project = experimentPart.getContainer().getGtsProject();

        experimentPart.setState(InternalState.DELETING);

        final StopGtsResourcesState stopState = new StopGtsResourcesState(project);
        setAndRunState(stopState);

        if(stopState.getStatus() == ExperimentTaskStatus.SUCCESS)
            experimentPart.setState(InternalState.DELETED);
        else
            experimentPart.setState(InternalState.FAILED);


        return null;
    }

    public final class StopGtsResourcesState extends SingleCallState<StopGtsResourcesTask>{

        protected StopGtsResourcesState(GtsXmlProject project) {
            super(gtsTaskFactory.createStopGtsResourcesTask(experimentPart.getReservation(), experimentPart.getType(), project));
        }
    }

}
