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

import be.iminds.ilabt.jfed.highlevel.controller.JFedHighLevelException;
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.highlevel.util.AggregateManagerWrapperFactory;
import be.iminds.ilabt.jfed.highlevel.util.SliceRegistryUtil;
import be.iminds.ilabt.jfed.lowlevel.ApiInfo;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.ilabt.jfed.lowlevel.api_wrapper.AggregateManagerWrapper;
import be.iminds.ilabt.jfed.fedmon.webapi.service.json.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;

/**
 * User: twalcari
 * Date: 6/17/2015
 * Time: 15:17
 */
public class DeleteSliversAtAuthorityTask extends Task {
    private static final Logger LOG = LoggerFactory.getLogger(DeleteSliversAtAuthorityTask.class);

    @Nonnull
    private final Slice slice;
    @Nonnull
    private final Server auth;

    private final AggregateManagerWrapperFactory aggregateManagerWrapperFactory;
    private final SliceRegistryUtil sliceRegistryUtil;

    public DeleteSliversAtAuthorityTask(@Nonnull Slice slice, @Nonnull Server authority,
                                        AggregateManagerWrapperFactory aggregateManagerWrapperFactory,
                                        SliceRegistryUtil sliceRegistryUtil) {
        super("Delete All Slivers on slice " + slice.getUrn() + "@" + authority.getName());
        this.slice = slice;
        this.auth = authority;
        this.aggregateManagerWrapperFactory = aggregateManagerWrapperFactory;
        this.sliceRegistryUtil = sliceRegistryUtil;
    }

    @Override
    protected void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        if (auth.isEdgeVlan())
            throw new JFedHighLevelException("Cannot delete resources at fake resource!");

        if (!ApiInfo.hasService(auth, ApiInfo.ApiName.GENI_AM)) {
            LOG.error("Slice has component manager '{}', but that authority has no known AM URL: cannot delete there.", auth.getDefaultComponentManagerUrn());
            throw new JFedHighLevelException("Slice.getDefaultComponentManagerUrn() manager \"" + auth.getDefaultComponentManagerUrn() + "\", " +
                    "but that authority has no known AM URL: cannot delete there.");
        }

        AggregateManagerWrapper amWrapper =
                aggregateManagerWrapperFactory.getAggregateManagerWrapper(taskExecution, auth);
        amWrapper.deleteSliver(slice.getUrn(), slice.getCredentials());

        sliceRegistryUtil.unregisterSliversAtSATaskExecution(slice, auth);
    }


    public Server getAuthority() {
        return auth;
    }
}
