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.lowlevel.JFedException;
import be.iminds.ilabt.jfed.lowlevel.api_wrapper.AggregateManagerWrapper;
import be.iminds.ilabt.jfed.fedmon.webapi.service.json.*;
import be.iminds.ilabt.jfed.util.GeniUrn;

import java.util.Collections;
import java.util.List;

/**
 * User: twalcari
 * Date: 6/17/2015
 * Time: 16:40
 */
public class RestartTask extends Task {
    private final Slice slice;
    private final Server auth;
    private final GeniUrn restartTarget;

    private final AggregateManagerWrapperFactory aggregateManagerWrapperFactory;
    private final HighLevelTaskFactory highLevelTaskFactory;

    public RestartTask(Slice slice, Server auth, GeniUrn restartTarget,
                       AggregateManagerWrapperFactory aggregateManagerWrapperFactory,
                       HighLevelTaskFactory highLevelTaskFactory) {
        super("Restart " + restartTarget);
        this.slice = slice;
        this.auth = auth;
        this.restartTarget = restartTarget;
        this.aggregateManagerWrapperFactory = aggregateManagerWrapperFactory;
        this.highLevelTaskFactory = highLevelTaskFactory;
    }

    @Override
    public void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        AggregateManagerWrapper amWrapper =
                aggregateManagerWrapperFactory.getAggregateManagerWrapper(taskExecution, auth);
        if (!amWrapper.isRestartSupported())
            throw new JFedHighLevelException("Authority " + auth.getDefaultComponentManagerUrn() + " does not support restart.");
        amWrapper.restart(restartTarget, slice.getCredentials());
    }

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