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

import be.iminds.ilabt.jfed.experiment.Experiment;
import be.iminds.ilabt.jfed.experiment.ExperimentPart;
import be.iminds.ilabt.jfed.experiment.SfaExperimentPart;
import be.iminds.ilabt.jfed.experiment.tasks.ExperimentTaskStatus;
import be.iminds.ilabt.jfed.highlevel.controller.TaskThread;
import be.iminds.ilabt.jfed.highlevel.jobs.states.JobStateFactory;
import be.iminds.ilabt.jfed.highlevel.model.Sliver;
import be.iminds.ilabt.jfed.highlevel.tasks.HighLevelTaskFactory;
import be.iminds.ilabt.jfed.highlevel.tasks.ReloadOSTask;

/**
 * User: twalcari
 * Date: 11/30/2015
 * Time: 11:11
 */
public class ReloadOSJob extends AbstractJob<Void> {

    private final Sliver sliver;
    private final JobStateFactory jobStateFactory;

    public ReloadOSJob(Experiment experiment, Sliver sliver, HighLevelTaskFactory hltf, TaskThread tt, JobStateFactory jobStateFactory) {
        super(String.format("Reload sliver %s", sliver.getUrn()), experiment, hltf, tt);
        this.sliver = sliver;
        this.jobStateFactory = jobStateFactory;
    }

    @Override
    public Void execute() throws Exception {

        final ReloadOSState reloadOSState = new ReloadOSState();
        setAndRunState(reloadOSState);

        if (reloadOSState.getStatus() == ExperimentTaskStatus.SUCCESS) {
            final ExperimentPart part = experiment.getPart(sliver);

            if(!(part instanceof SfaExperimentPart))
                throw new UnsupportedOperationException("Can only reload OS on SfaExperimentPart!");

            setAndRunState(jobStateFactory.createGetStatusUntilReadyOrFailTaskState(this, (SfaExperimentPart) part));
        }
        else {
            updateMessage(String.format("Reloading sliver '%s' failed.", sliver.getUrn()));
        }
        return null;
    }

    private class ReloadOSState extends SingleCallState<ReloadOSTask> {

        protected ReloadOSState() {
            super(String.format("Reload sliver %s", sliver.getUrnString()), hltf.reloadOS(sliver));
        }
    }
}
