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.highlevel.model.Slice;
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.ReputationService;
import be.iminds.ilabt.jfed.lowlevel.api.RestApi;
import be.iminds.ilabt.jfed.lowlevel.connection.JFedConnectionProvider;
import be.iminds.ilabt.jfed.preferences.JFedPreferences;
import be.iminds.ilabt.jfed.util.JavaFXLogger;

import java.util.Date;
import java.util.List;

/**
 * User: twalcari
 * Date: 1/11/2016
 * Time: 11:38
 */
public class ListPendingReputationQuestionnairesTask extends ReputationTask {

    private final Slice slice;

    private List<ReputationService.SliceReputation> pendingQuestionnaires;

    public ListPendingReputationQuestionnairesTask(Slice slice, JavaFXLogger logger, JFedPreferences jFedPreferences,
                                                   TestbedInfoSource testbedInfoSource, JFedConnectionProvider connectionProvider,
                                                   GeniUserProvider geniUserProvider) {
        super("Requesting pending reputation questionnaires",
                logger, jFedPreferences, testbedInfoSource,
                connectionProvider, geniUserProvider);

        this.slice = slice;
    }

    @Override
    protected void doReputationTask(TaskExecution taskExecution, ReputationService reputationService) throws JFedException {
        if (slice.getCreationDate() == null || slice.getExpirationDate() == null || slice.getUrn() == null) {
            throw new RuntimeException("Cannot register Reputation questionaire: some slice info is missing. (this is an internal jFed error)"+
                    (slice.getCreationDate() == null ? " cd" : "")+
                    (slice.getExpirationDate() == null ? " ed" : "")+
                    (slice.getUrn() == null ? " u" : "")
            );
        }

        RestApi.RestReply<List<ReputationService.SliceReputation>> reply =
                reputationService.registerExperiment(
                        createConnection(),
                        geniUserProvider.getLoggedInGeniUser().getUserUrn(),
                        slice.getUrn(),
                        Date.from(slice.getCreationDate()),
                        Date.from(slice.getExpirationDate()));

        if (reply.getHttpCallDetails().getResultHttpStatusCode() != 200) {
            throw new JFedHighLevelException("Error while registering experiment to reputation service");
        }

        pendingQuestionnaires = reply.getValue();
    }

    public List<ReputationService.SliceReputation> getPendingQuestionnaires() {
        return pendingQuestionnaires;
    }
}
