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 be.iminds.ilabt.jfed.util.GeniUrn;

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

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

    //input parameters
    private final Server auth;
    private final GeniUrn imageUrn;

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

    public DeleteImageTask(Server auth, GeniUrn imageUrn,
                           UserAndSliceApiWrapper userAndSliceApiWrapper,
                           AggregateManagerWrapperFactory aggregateManagerWrapperFactory,
                           HighLevelTaskFactory highLevelTaskFactory) {
        super("Delete Image " + imageUrn + " on " + auth.getDefaultComponentManagerUrn());
        this.auth = auth;
        this.imageUrn = imageUrn;
        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 JFedHighLevelException("UserAndSliceApiWrapper did not have user Credentials.");

        amWrapper.deleteImage(userAndSliceApiWrapper.getCachedUserCredentialsForAM(), imageUrn);
    }

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