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 com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.name.Names;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Named;
import java.util.Properties;

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

    private final Properties contextFileProperties;

    public BaseCliContextFileUserModule(Properties contextFileProperties) {
        this.contextFileProperties = contextFileProperties;
    }

    @Override
    protected void configure() {
        bind(Properties.class).annotatedWith(Names.named("contextFileProperties")).toInstance(contextFileProperties);
        bind(ContextFile.class);
    }

    @Provides
    public GeniUser provideGeniUser(final ContextFile contextFile) {
        try {
            return contextFile.getUser();
        } catch (ContextFile.ContextFileException e) {
            throw new RuntimeException("Error getting user from context file", e);
        }
    }

    @Provides
    @Named("userServer")
    public Server provideUserAuthority(final GeniUser geniUser) {
        return geniUser.getUserAuthorityServer();
    }

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

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