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.GeniUrn;
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.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

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

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

    protected final UserAndSliceApiWrapper userAndSliceApiWrapper;
    protected final JavaFXLogger logger;
    protected final HighLevelTaskFactory highLevelTaskFactory;

    protected RenewTask(String name, @Nonnull Slice slice, @Nonnull Instant newExpirationDate,
                        UserAndSliceApiWrapper userAndSliceApiWrapper,
                        JavaFXLogger logger, HighLevelTaskFactory highLevelTaskFactory) {
        super(name);
        this.slice = slice;
        this.newExpirationDate = newExpirationDate;
        this.userAndSliceApiWrapper = userAndSliceApiWrapper;
        this.logger = logger;
        this.highLevelTaskFactory = highLevelTaskFactory;
    }

    protected void updateSlivers(Collection<GeniUrn> sliverUrns, TaskExecution taskExecution) throws JFedException {
        if (!userAndSliceApiWrapper.isRegisterAggregatesForSliceSupported()) {
            LOG.debug("UpdateSliversTask: This SA does not support updating sliver info. Doing nothing.");
            return;
        }

        //Date sliceExpiration = slice.getExpirationDate();
        LOG.debug("UpdateSliversTask has {}sliver Urns to update.", sliverUrns.size());
        if (!sliverUrns.isEmpty())
            userAndSliceApiWrapper.updateSliverExpirationDateInfoForSlice(JavaFXLogger.wrap(logger, taskExecution),
                    slice.getCredentials(), slice.getUrn(),
                    sliverUrns, Date.from(newExpirationDate));
    }


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


}
