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.Sliver;
import be.iminds.ilabt.jfed.highlevel.util.AggregateManagerWrapperFactory;
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 java.util.Collections;
import java.util.List;

/**
 * User: twalcari
 * Date: 6/16/2015
 * Time: 17:14
 */
public class SliverManifestTask extends Task {
    private final Sliver sliver;

    //environment parameters
    private final AggregateManagerWrapperFactory aggregateManagerWrapperFactory;
    private final HighLevelTaskFactory highLevelTaskFactory;

    public SliverManifestTask(Sliver sliver, AggregateManagerWrapperFactory aggregateManagerWrapperFactory, HighLevelTaskFactory highLevelTaskFactory) {
        super("Get Sliver Manifest");
        this.sliver = sliver;
        this.aggregateManagerWrapperFactory = aggregateManagerWrapperFactory;
        this.highLevelTaskFactory = highLevelTaskFactory;
    }

    @Override
    public void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        Server auth = sliver.getServer();

        if (!ApiInfo.hasService(auth, ApiInfo.ApiName.GENI_AM)) {
            throw new JFedHighLevelException("Tried to get manifest for sliver \"" + sliver.getUrnString() + "\", " +
                    "at authority \"" + auth.getDefaultComponentManagerUrn() + "\", but that authority has no AM URL: cannot continue.");
        }

        AggregateManagerWrapper amWrapper =
                aggregateManagerWrapperFactory.getAggregateManagerWrapper(taskExecution, auth);
        amWrapper.describe(sliver.getSlice().getUrn(), sliver.getSlice().getCredentials());
    }

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