package be.iminds.jfed.gts_highlevel.tasks;

import be.iminds.ilabt.jfed.highlevel.controller.TaskExecution;
import be.iminds.ilabt.jfed.util.JavaFXLogger;
import be.iminds.jfed.gts_highlevel.controller.GtsException;
import be.iminds.jfed.gts_highlevel.controller.GtsModel;
import be.iminds.jfed.gts_highlevel.controller.GtsReservationManager;
import be.iminds.jfed.gts_highlevel.controller.GtsReservationManagerFactory;
import be.iminds.jfed.gts_highlevel.model.GtsXmlProject;
import be.iminds.jfed.gts_highlevel.model.GtsXmlReservation;

import javax.inject.Provider;
import java.util.List;

/**
 * User: twalcari
 * Date: 1/28/2016
 * Time: 11:31
 */
public class UpdateGtsReservationTask extends LoggedInGtsTask {

    private final GtsXmlProject project;
    private final int reservationId;

    private GtsXmlReservation result;

    public UpdateGtsReservationTask(GtsXmlProject project, int reservationId, GtsReservationManagerFactory gtsReservationManagerFactory,
                                    Provider<GtsLoginTask> loginGtsTaskProvider, GtsModel gtsModel,
                                    JavaFXLogger logger) {
        super("Update GTS Reservation '" + reservationId + "'", logger, gtsReservationManagerFactory, loginGtsTaskProvider, gtsModel);
        this.project = project;
        this.reservationId = reservationId;
    }


    @Override
    protected void doGtsRMTask(TaskExecution taskExecution, GtsReservationManager reservationManager) throws GtsException {

        List<GtsXmlReservation> reservations = reservationManager.listReservations(project);

        result = reservations.stream()
                .filter(newRes -> newRes.getId() == reservationId)
                .findFirst()
                .orElseThrow(() -> new GtsException("Could not find reservation " + reservationId + " in project " + project.getId()));

    }

    public boolean isFinalState(){
        return result != null && isFinalState(result.getStatus());
    }

    private static boolean isFinalState(GtsXmlReservation.Status status) {
        return status == GtsXmlReservation.Status.ACTIVE ||
                status == GtsXmlReservation.Status.DEACTIVED ||
                status == GtsXmlReservation.Status.FAILURE;
    }


    public GtsXmlReservation getResult() {
        return result;
    }
}
