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

import be.iminds.ilabt.jfed.highlevel.controller.JFedHighLevelException;
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.TestbedInfoSource;
import be.iminds.ilabt.jfed.lowlevel.api.RestApi;
import be.iminds.ilabt.jfed.lowlevel.api.SlaCollector;
import be.iminds.ilabt.jfed.lowlevel.connection.JFedConnectionProvider;
import be.iminds.ilabt.jfed.preferences.JFedPreferences;
import be.iminds.ilabt.jfed.util.JavaFXLogger;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;

/**
 * User: twalcari
 * Date: 10/29/2015
 * Time: 16:29
 */
public class RequestSlaUuidTask extends SlaTask {
    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(RegisterSliversTask.class);
    private static final String AGREEMENT_ID = "agreement_id";
    private String slaUuid = null;

    public RequestSlaUuidTask(JavaFXLogger logger, JFedPreferences jFedPreferences, TestbedInfoSource testbedInfoSource,
                              JFedConnectionProvider connectionProvider, GeniUserProvider geniUserProvider) {
        super("Request SLA UUID", logger, jFedPreferences, testbedInfoSource, connectionProvider, geniUserProvider);
    }

    @Override
    protected void doSlaTask(TaskExecution taskExecution, SlaCollector slaCollector) throws JFedException {
        RestApi.RestReply<String> reply = slaCollector.generateUUID(createConnection());

        if (reply.getValue() != null) {
            try {
                JSONObject result = new JSONObject(reply.getValue());

                slaUuid = result.getString(AGREEMENT_ID);
            } catch (JSONException ex) {
                throw new JFedHighLevelException("Could not process response: " + ex.getMessage(), ex);
            }
        }

        if (slaUuid == null) {
            LOG.error("Didn't get a UUID from the server!");
        }
    }


    public String getSlaUuid() {
        return slaUuid;
    }
}
