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.LoginController;
import be.iminds.jfed.gts_highlevel.controller.LoginControllerFactory;
import be.iminds.jfed.gts_highlevel.model.GtsCredentials;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.time.Duration;
import java.time.Instant;

/**
 * User: twalcari
 * Date: 9/24/2015
 * Time: 15:42
 */
@Singleton
public class GtsLoginTask extends GtsTask {

    private static final Duration MAX_CREDENTIAL_LIFETIME = Duration.ofMinutes(10);

    private final LoginControllerFactory loginControllerFactory;
    private final GtsModel gtsModel;
    private final JavaFXLogger logger;
    private GtsCredentials gtsCredentials = null;
    private Instant lastExecution = null;

    @Inject
    GtsLoginTask(LoginControllerFactory loginControllerFactory, GtsModel gtsModel, JavaFXLogger logger) {
        super("GTS Login");
        this.loginControllerFactory = loginControllerFactory;
        this.gtsModel = gtsModel;
        this.logger = logger;
    }


    @Override
    protected void doGtsTask(TaskExecution taskExecution) throws GtsException {
        LoginController loginController = getLoginController(taskExecution);
        gtsCredentials = loginController.login();

        gtsModel.setCredentials(gtsCredentials);
        lastExecution = Instant.now();
    }

    private LoginController getLoginController(TaskExecution taskExecution) {
        return loginControllerFactory.createLoginController(JavaFXLogger.wrap(logger, taskExecution));
    }

    public GtsCredentials getGtsCredentials() {
        return gtsCredentials;
    }

    @Override
    public boolean newExecutionNeeded() {
        return gtsModel.getCredentials() == null
                || lastExecution == null
                || Duration.between(lastExecution, Instant.now()).compareTo(MAX_CREDENTIAL_LIFETIME) > 0;
    }
}
