package be.iminds.jfed.gts_highlevel.controller;

import be.iminds.ilabt.jfed.lowlevel.JFedException;
import be.iminds.ilabt.jfed.lowlevel.api.RestApi;
import be.iminds.jfed.gts_highlevel.GtsService;
import be.iminds.jfed.gts_highlevel.model.GtsCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * User: twalcari
 * Date: 9/22/2015
 * Time: 12:10
 */
public class LoginController {
    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    private final GtsService gtsService;
    private final GtsConnectionProvider gtsConnectionProvider;


    LoginController(GtsService gtsService, @GtsLoginConnectionProvider GtsConnectionProvider gtsConnectionProvider) {
        this.gtsService = gtsService;
        this.gtsConnectionProvider = gtsConnectionProvider;
    }


    public GtsCredentials login() throws GtsException {
        if (gtsConnectionProvider instanceof GtsConnectionProviderImpl
                && !((GtsConnectionProviderImpl) gtsConnectionProvider).hasValidConfig()) {
            LOG.warn("Skipping login because we don't have a login-service available");
            return new GtsCredentials("DUMMY");
        }

        RestApi.RestReply<String> reply = null;
        try {
            reply = gtsService.login(gtsConnectionProvider.getConnection());

            if (reply != null && reply.getHttpCallDetails().getResultHttpStatusCode() == 200 && reply.getValue() != null) {
                assert !Objects.equals("", reply.getValue());
                return new GtsCredentials(reply.getValue());
            } else {
                throw new GtsException("Could not login onto GTS. Please check your credentials.");
            }

        } catch (JFedException e) {
            throw new GtsException("Exception while logging in.", e, reply);
        }
    }


}
