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.controller.TaskThread;
import be.iminds.ilabt.jfed.highlevel.model.Slice;
import be.iminds.ilabt.jfed.lowlevel.ApiInfo;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.ilabt.jfed.fedmon.webapi.service.json.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.List;

/**
 * User: twalcari
 * Date: 6/16/2015
 * Time: 16:47
 */
public class SliceManifestTask extends Task {
    private static final Logger LOG = LoggerFactory.getLogger(SliceManifestTask.class);
    private final Slice slice;


    private final TaskThread tt;
    private final HighLevelTaskFactory highLevelTaskFactory;

    public SliceManifestTask(@Nonnull Slice slice, TaskThread tt, HighLevelTaskFactory highLevelTaskFactory) {
        super("Get Slice Manifest");
        this.slice = slice;
        this.tt = tt;
        this.highLevelTaskFactory = highLevelTaskFactory;
    }

    @Override
    public void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        LOG.debug("getManifest cm count: " + slice.getManifestComponentManagers().size());
        for (Server server : slice.getManifestComponentManagers())
            if (ApiInfo.hasService(server, ApiInfo.ApiName.GENI_AM)) {
                //TODO: see getStatus, here as well we need to block ourself and add these as deps instead of just adding them
                SliceManifestForAuthorityTask subCall = highLevelTaskFactory.getSliceManifest(slice, server);
                tt.addTask(subCall);
            } else
                LOG.error("Tried to get manifest for slice \"" + slice.getUrn() + "\", at server \"" + server.getDefaultComponentManagerUrn() + "\", but that server has no AM URL: will ignore slice on this authority.");
    }

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

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