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.model.Sliver;
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 java.net.URL;
import java.util.Collections;
import java.util.List;

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

    private URL url = null;

    private final AggregateManagerWrapperFactory aggregateManagerWrapperFactory;
    private final HighLevelTaskFactory highLevelTaskFactory;

    public OpenConsoleTask(Sliver sliver,
                           AggregateManagerWrapperFactory aggregateManagerWrapperFactory,
                           HighLevelTaskFactory highLevelTaskFactory) {
        super("Get Console URL for sliver " + sliver.getUrn());
        this.sliver = sliver;
        this.aggregateManagerWrapperFactory = aggregateManagerWrapperFactory;
        this.highLevelTaskFactory = highLevelTaskFactory;
    }

    @Override
    public void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        Server auth = sliver.getServer();
        Slice slice = sliver.getSlice();
        AggregateManagerWrapper amWrapper =
                aggregateManagerWrapperFactory.getAggregateManagerWrapper(taskExecution, auth);
        if (!amWrapper.isOpenConsoleSupported())
            throw new JFedHighLevelException("Authority " + auth.getDefaultComponentManagerUrn() + " does not support open console.");

        this.url = amWrapper.openConsole(sliver.getUrn(), slice.getCredentials());
    }

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

    public URL getUrl() {
        return url;
    }
}
