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.SlaCollector;
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 SlaTask extends Task {

    private static final String SLA_COLLECTOR_ID = "slacollector";

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

    protected final GeniUserProvider geniUserProvider;

    public SlaTask(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 slaTestbed = testbedInfoSource.getTestbedById(SLA_COLLECTOR_ID);
        Server slaAuth = slaTestbed.getDefaultServer();

        if (slaAuth == null)
            throw new JFedHighLevelException("No SLA Collector authority defined! Check your testbeds.xml");


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

    @Override
    protected final void doTask(TaskExecution taskExecution) throws JFedException, InterruptedException {
        final SlaCollector slaCollector = new SlaCollector(JavaFXLogger.wrap(logger, taskExecution), jFedPreferences);
        doSlaTask(taskExecution, slaCollector);

    }

    protected abstract void doSlaTask(TaskExecution taskExecution, SlaCollector slaCollector) throws JFedException;

}
