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

import be.iminds.ilabt.jfed.highlevel.controller.Task;
import be.iminds.ilabt.jfed.highlevel.controller.TaskExecution;
import be.iminds.ilabt.jfed.highlevel.model.Slice;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.ilabt.jfed.lowlevel.api_wrapper.UserAndSliceApiWrapper;
import be.iminds.ilabt.jfed.util.JavaFXLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.time.Instant;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * User: twalcari
 * Date: 6/17/2015
 * Time: 14:42
 */
public final class RenewSliceTask extends RenewTask {
    private static final Logger LOG = LoggerFactory.getLogger(RenewSliceTask.class);

    @Nonnull
    private final Slice slice;
    @Nonnull
    private final Instant newExpirationDate;

    public RenewSliceTask(@Nonnull Slice slice, @Nonnull Instant newExpirationDate,
                          UserAndSliceApiWrapper userAndSliceApiWrapper,
                          JavaFXLogger logger, HighLevelTaskFactory highLevelTaskFactory) {
        super("Renew Slice", slice, newExpirationDate, userAndSliceApiWrapper, logger, highLevelTaskFactory);
        this.slice = slice;
        this.newExpirationDate = newExpirationDate;
    }

    @Override
    protected void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        if (slice.getExpirationDate() == null || slice.getExpirationDate().isBefore(newExpirationDate)) {
            try {
                userAndSliceApiWrapper.renewSlice(JavaFXLogger.wrap(logger, taskExecution), slice.getCredentials(), Date.from(newExpirationDate));
            } catch (Exception e) {
                LOG.error("Failed to renew slice: " + e.getMessage(), e);

                //failure to renew slice will normally cause failure to renew slivers
                if (slice.getExpirationDate() == null || slice.getExpirationDate().isBefore(newExpirationDate))
                    if (e instanceof JFedException)
                        throw (JFedException) e;
                    else
                        throw new JFedException("Failed to renew slice " + slice.getUrn(), e);
            }
        } else
            LOG.info("Not renewing slice: new expiration date (" + newExpirationDate + ") is not after current expiration date (" + slice.getExpirationDate() + ")");
    }

    @Override
    public List<Task> initAlwaysDependsOn() {
        return Collections.singletonList(highLevelTaskFactory.getAggregatesForSlice(slice));
    }
}
