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 javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;

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

    private final AggregateManagerWrapperFactory aggregateManagerWrapperFactory;
    private final HighLevelTaskFactory highLevelTaskFactory;

    public SliverStatusTask(@Nonnull Sliver sliver,
                            AggregateManagerWrapperFactory aggregateManagerWrapperFactory,
                            HighLevelTaskFactory highLevelTaskFactory) {
        super("Get Sliver Status @ " + sliver.getServer().getDefaultComponentManagerUrn());
        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 Status for sliver \"" + sliver.getUrnString() + "\", " +
                    "at authority \"" + auth.getDefaultComponentManagerUrn() + "\", but that authority has no AM URL: cannot continue.");
        }

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

    }

    @Override
    public List<Task> initDependsOn() {
        List<Task> res = new ArrayList<>();
        res.add(highLevelTaskFactory.getSliceCredential(sliver.getSlice()));
        return res;
    }
}
