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

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * User: twalcari
 * Date: 6/17/2015
 * Time: 16:36
 */
public class EditSSHKeysTask extends Task {
    //input parameters
    private final Slice slice;
    private final Server auth;
    private final Collection<UserSpec> userSpecs;

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

    public EditSSHKeysTask(Slice slice, Server auth, Collection<UserSpec> userSpecs,
                           AggregateManagerWrapperFactory aggregateManagerWrapperFactory, HighLevelTaskFactory highLevelTaskFactory) {
        super("Edit SSH Keys");
        this.slice = slice;
        this.auth = auth;
        this.userSpecs = userSpecs;
        this.aggregateManagerWrapperFactory = aggregateManagerWrapperFactory;
        this.highLevelTaskFactory = highLevelTaskFactory;
    }

    @Override
    public void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        AggregateManagerWrapper amWrapper =
                aggregateManagerWrapperFactory.getAggregateManagerWrapper(taskExecution, auth);
        if (!amWrapper.isEditSshKeysSupported())
            throw new JFedHighLevelException("Authority " + auth.getDefaultComponentManagerUrn() + " does not support edit of SSH keys.");

        amWrapper.editSshKeys(slice.getUrn(), slice.getCredentials(), userSpecs);
    }

    @Override
    public List<Task> initDependsOn() {
        List<Task> res = new ArrayList<>();
        res.add(highLevelTaskFactory.getSliceCredential(slice));
        return res;
    }
}
