package be.iminds.ilabt.jfed.highlevel;

import be.iminds.ilabt.jfed.lowlevel.authority.AuthorityFinder;
import be.iminds.ilabt.jfed.lowlevel.user.GeniUserFactory;
import be.iminds.ilabt.jfed.lowlevel.user.PreferencesUserLoginInfoManager;
import be.iminds.ilabt.jfed.lowlevel.user.UserLoginInfoManager;
import be.iminds.ilabt.jfed.util.JFedUtils;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.name.Names;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;

/**
 * User: twalcari
 * Date: 11/27/2014
 * Time: 16:34
 */
public class UserLoginModelModule extends AbstractModule {
    private static final Logger LOG = LoggerFactory.getLogger(UserLoginModelModule.class);

    private final boolean loginRequiresAlluserInfo;

    public UserLoginModelModule(boolean loginRequiresAlluserInfo) {
        this.loginRequiresAlluserInfo = loginRequiresAlluserInfo;
    }

    @Provides
    @Singleton
    @Named("login")
    public PropertiesConfiguration provideLoginConfiguration() {
        PropertiesConfiguration config = null;
        try {
            String userDataDir = JFedUtils.getUserDataDirectory();

            if (userDataDir == null) {
                LOG.error("Could not access user data directory. Do you have sufficient rights to access the file system?");
            }
            File propertiesFile = new File(userDataDir, "login.properties");

            config = new PropertiesConfiguration(propertiesFile);
            config.setAutoSave(true);
        } catch (ConfigurationException e) {
            LOG.error("Could not create PropertiesConfiguration", e);
        }

        return config;
    }

    @Provides
    @Singleton
    public UserLoginInfoManager provideUserLoginModelManager(
            @Named("login") PropertiesConfiguration configuration,
            GeniUserFactory geniUserFactory,
            AuthorityFinder authorityFinder) {
        return new PreferencesUserLoginInfoManager(configuration, geniUserFactory, authorityFinder);
    }

    @Override
    protected void configure() {
        bind(Boolean.class).annotatedWith(Names.named("loginRequiresAlluserInfo")).toInstance(loginRequiresAlluserInfo);
    }
}
