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.*;
import be.iminds.ilabt.jfed.lowlevel.api.ReputationService;
import be.iminds.ilabt.jfed.fedmon.webapi.service.json.*;
import be.iminds.ilabt.jfed.lowlevel.connection.HttpConnection;
import be.iminds.ilabt.jfed.lowlevel.connection.JFedConnectionProvider;
import be.iminds.ilabt.jfed.preferences.JFedPreferences;
import be.iminds.ilabt.jfed.util.JavaFXLogger;

/**
 * User: twalcari
 * Date: 10/29/2015
 * Time: 17:07
 */
public abstract class ReputationTask extends Task {
    private static final String REPUTATION_SERVICE_ID = "reputationservice";

    private final JavaFXLogger logger;
    private final JFedPreferences jFedPreferences;
    private final TestbedInfoSource testbedInfoSource;
    private final JFedConnectionProvider connectionProvider;

    protected final GeniUserProvider geniUserProvider;

    public ReputationTask(String name, JavaFXLogger logger,
                          JFedPreferences jFedPreferences, TestbedInfoSource testbedInfoSource,
                          JFedConnectionProvider connectionProvider, GeniUserProvider geniUserProvider) {
        super(name);
        this.logger = logger;
        this.jFedPreferences = jFedPreferences;
        this.testbedInfoSource = testbedInfoSource;
        this.connectionProvider = connectionProvider;
        this.geniUserProvider = geniUserProvider;
    }


    protected HttpConnection createConnection() throws JFedException {
        Testbed reputationServiceTestbed = testbedInfoSource.getTestbedById(REPUTATION_SERVICE_ID);
        Server reputationServer = reputationServiceTestbed.getDefaultServer();
        if (reputationServer == null)
            throw new JFedHighLevelException("No reputation server defined! Check your testbeds.xml");

        final GeniUser loggedInGeniUser = geniUserProvider.getLoggedInGeniUser();
        return (HttpConnection) connectionProvider.getConnectionByAuthority(loggedInGeniUser, reputationServer, new ApiInfo.Api(ApiInfo.ApiName.FED4FIRE_REPUTATION_SERVICE, 1));
    }

    @Override
    protected final void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        final ReputationService reputationService = new ReputationService(JavaFXLogger.wrap(logger, taskExecution), jFedPreferences);
        doReputationTask(taskExecution, reputationService);

    }

    protected abstract void doReputationTask(TaskExecution taskExecution, ReputationService reputationService) throws JFedException;

}
