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

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

/**
 * User: twalcari
 * Date: 6/17/2015
 * Time: 16:20
 */
public class ListDiskImagesTask extends Task {

    //input parameters
    private final Server auth;

    //results
    private List<AggregateManagerWrapper.ImageInfo> diskImageInfos = null;

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

    public ListDiskImagesTask(Server auth, UserAndSliceApiWrapper userAndSliceApiWrapper,
                              AggregateManagerWrapperFactory aggregateManagerWrapperFactory,
                              HighLevelTaskFactory highLevelTaskFactory) {
        super("List User Images on " + auth.getName());
        this.auth = auth;
        this.userAndSliceApiWrapper = userAndSliceApiWrapper;
        this.aggregateManagerWrapperFactory = aggregateManagerWrapperFactory;
        this.highLevelTaskFactory = highLevelTaskFactory;
    }

    @Override
    protected void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        AggregateManagerWrapper amWrapper =
                aggregateManagerWrapperFactory.getAggregateManagerWrapper(taskExecution, auth);
        if (!amWrapper.areUserDiskImageFunctionsSupported())
            throw new JFedHighLevelException("Authority " + auth.getDefaultComponentManagerUrn() + " does not support list image.");

        if (!userAndSliceApiWrapper.hasUserCredentials())
            throw new JFedException("UserAndSliceApiWrapper did not have user Credentials.");

        List<AggregateManagerWrapper.ImageInfo> imageInfos =
                amWrapper.listImages(userAndSliceApiWrapper.getCachedUserCredentialsForAM());
        diskImageInfos = Collections.unmodifiableList(imageInfos);
    }

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

    public List<AggregateManagerWrapper.ImageInfo> getDiskImageInfos() {
        return diskImageInfos;
    }
}
