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.lowlevel.GeniUserProvider;
import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.ilabt.jfed.lowlevel.ApiInfo;
import be.iminds.ilabt.jfed.lowlevel.api.AbstractFederationApi;
import be.iminds.ilabt.jfed.lowlevel.api.FederationRegistryApi1;
import be.iminds.ilabt.jfed.fedmon.webapi.service.json.*;
import be.iminds.ilabt.jfed.lowlevel.connection.JFedConnectionProvider;
import be.iminds.ilabt.jfed.lowlevel.connection.SfaConnection;
import be.iminds.ilabt.jfed.preferences.JFedPreferences;
import be.iminds.ilabt.jfed.util.JavaFXLogger;

import java.util.List;

/**
 * User: twalcari
 * Date: 6/17/2015
 * Time: 11:17
 */
public class EmulabRegistryTask extends Task {
    private final Server auth;

    private final JavaFXLogger logger;
    private final GeniUserProvider geniUserProvider;
    private final JFedPreferences jFedPreferences;
    private final JFedConnectionProvider connectionProvider;


    public EmulabRegistryTask(Server auth, JavaFXLogger logger, GeniUserProvider geniUserProvider,
                              JFedPreferences jFedPreferences, JFedConnectionProvider connectionProvider) {
        super("Emulab Registry " + auth.getName());
        this.auth = auth;
        this.logger = logger;
        this.geniUserProvider = geniUserProvider;
        this.jFedPreferences = jFedPreferences;
        this.connectionProvider = connectionProvider;
    }

    @Override
    public void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        FederationRegistryApi1 registryApi =
                new FederationRegistryApi1(JavaFXLogger.wrap(logger, taskExecution), jFedPreferences);

        SfaConnection conn =
                (SfaConnection) connectionProvider.getConnectionByAuthority(geniUserProvider.getLoggedInGeniUser(),
                        auth,
                        new ApiInfo.Api(ApiInfo.ApiName.GENI_CH, 1));
        if (conn == null)
            throw new JFedHighLevelException("No connection can be created. Perhaps the authority \"" + auth.getDefaultComponentManagerUrn() + "\" does not have a federation registry?");

        AbstractFederationApi.FederationApiReply<List<FederationRegistryApi1.ServiceDetails>> reply =
                registryApi.lookupAggregates(conn, null, null, null);

        if (!reply.getGeniResponseCode().isSuccess()) throw new JFedException("reply not success");
    }
}
