package be.iminds.ilabt.jfed.highlevel.tasks;

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.lowlevel.JFedException;
import be.iminds.ilabt.jfed.lowlevel.api.user_spec.UserSpec;
import be.iminds.ilabt.jfed.lowlevel.api_wrapper.UserAndSliceApiWrapper;
import be.iminds.ilabt.jfed.util.GeniUrn;
import be.iminds.ilabt.jfed.util.JavaFXLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * User: twalcari
 * Date: 6/16/2015
 * Time: 17:47
 */
public class SliceMembersSshKeysTask extends Task {
    private static final Logger LOG = LoggerFactory.getLogger(SliceMembersSshKeysTask.class);

    private final Slice slice;
    private final GeniUrn sliceUrn;

    private List<UserSpec> userSpecs = null;

    private final UserAndSliceApiWrapper userAndSliceApiWrapper;
    private final JavaFXLogger logger;
    private final HighLevelTaskFactory highLevelTaskFactory;

    public SliceMembersSshKeysTask(@Nonnull Slice slice, UserAndSliceApiWrapper userAndSliceApiWrapper,
                                   JavaFXLogger logger, HighLevelTaskFactory highLevelTaskFactory) {
        super("Get User SSH Keys For users in slice " + slice.getUrn());
        this.slice = slice;
        this.userAndSliceApiWrapper = userAndSliceApiWrapper;
        this.logger = logger;
        this.highLevelTaskFactory = highLevelTaskFactory;
        this.sliceUrn = slice.getUrn();
        assert sliceUrn != null;
    }

    @Override
    public void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        List<GeniUrn> userUrns =
                userAndSliceApiWrapper.getUsersForSlice(JavaFXLogger.wrap(logger, taskExecution), sliceUrn, slice.getCredentials());
        if (userUrns == null) userUrns = Collections.emptyList();

        userSpecs = new ArrayList<>();
        for (GeniUrn userUrn : userUrns) {
            assert (userUrn != null);
            try {
                List<String> userKeys =
                        userAndSliceApiWrapper.getSshKeysForUser(JavaFXLogger.wrap(logger, taskExecution), userUrn);
                if (userKeys != null)
                    userSpecs.add(new UserSpec(userUrn.toString(), userKeys));
            } catch (JFedException e) {
                LOG.warn("Could not get user key for {}", userUrn, e);
            }
        }
    }

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

    public List<UserSpec> getUserSpecs() {
        return userSpecs;
    }
}
