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

import be.iminds.ilabt.jfed.experiment.SfaExperimentPart;
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.tasks.HighLevelTaskFactory;
import be.iminds.ilabt.jfed.highlevel.tasks.RenewSliversTask;
import be.iminds.ilabt.jfed.lowlevel.JFedException;

import java.time.Instant;

/**
 * User: twalcari
 * Date: 1/13/2016
 * Time: 16:10
 */
public class RenewSfaExperimentPartStateSlice extends ExperimentPartStateSlice<SfaExperimentPart> {

    private final Instant newExpirationDate;

    private final HighLevelTaskFactory hltf;


    public RenewSfaExperimentPartStateSlice(Job<?> job, SfaExperimentPart experimentPart, Instant newExpirationDate, HighLevelTaskFactory hltf) {
        super(job, experimentPart);
        this.newExpirationDate = newExpirationDate;
        this.hltf = hltf;
    }

    @Override
    public ExperimentTaskStatus statefulRun() throws JFedException, InterruptedException {
        RenewSfaExperimentPartState renewState = new RenewSfaExperimentPartState(experimentPart);
        setAndRunState(renewState);

        return renewState.getStatus();
    }


    private class RenewSfaExperimentPartState extends SingleCallState<RenewSliversTask> {

        protected RenewSfaExperimentPartState(SfaExperimentPart experimentPart) {
            super(String.format("Renewing resources on %s", experimentPart.getName()),
                    hltf.renewSliversAtAuthority(experiment.getSlice(), newExpirationDate, experimentPart.getConnectSfaAuthority()));
        }

    }
}
