package be.iminds.ilabt.jfed.ui.commandline;

import be.iminds.ilabt.jfed.fedmon.webapi.service.json.Server;
import be.iminds.ilabt.jfed.lowlevel.GeniUser;
import be.iminds.ilabt.jfed.lowlevel.GeniUserProvider;
import be.iminds.ilabt.jfed.lowlevel.user.GeniUserFactory;
import be.iminds.ilabt.jfed.lowlevel.userloginmodel.InvalidLoginException;
import be.iminds.ilabt.jfed.util.GeniUrn;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;

/**
 * BaseCliModule
 */
public class BaseCliKeyCertUserModule extends AbstractModule {
    private final static Logger LOG = LoggerFactory.getLogger(BaseCliKeyCertUserModule.class);

    private final String keyCertContent;
    private final char[] keyPass;
    private final File certificateKeyFile;
    private final File privateKeyFile;

    public BaseCliKeyCertUserModule(@Nonnull String keyCertContent, @Nullable char[] keyPass,
                                    @Nonnull File certificateKeyFile, @Nonnull File privateKeyFile) {
        this.keyCertContent = keyCertContent;
        this.keyPass = keyPass;
        this.certificateKeyFile = certificateKeyFile;
        this.privateKeyFile = privateKeyFile;
    }

    @Provides
    @Singleton
    public GeniUser getGeniUser(GeniUserFactory geniUserFactory) {
        try {
            return geniUserFactory.createGeniUser(keyCertContent, keyPass, certificateKeyFile, privateKeyFile);
        } catch (InvalidLoginException e) {
            LOG.error("Could not login the user", e);
            return null;
        }
    }

    @Provides
    @Singleton
    @Named("userUrn")
    public GeniUrn getUserUrn(GeniUser geniUser) {
        if (geniUser != null)
            return geniUser.getUserUrn();
        else
            return null;
    }

    @Provides
    @Named("userServer")
    public Server provideGeniUserServer(GeniUser geniUser) {
        if (geniUser != null)
            return geniUser.getUserAuthorityServer();
        else
            return null;
    }

    @Provides
    public GeniUserProvider provideGeniUserProvider(final GeniUser geniUser) {
        return new GeniUserProvider() {
            @Override
            public GeniUser getLoggedInGeniUser() {
                return geniUser;
            }

            @Override
            public boolean isUserLoggedIn() {
                return geniUser != null;
            }
        };
    }

    @Override
    protected void configure() {

    }
}
