package com.telephoners.krakyournet.ctf.modules;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.core.ApplicationConfiguration;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;

import java.net.MalformedURLException;

//tdo: split modules
public class ApplicationModule extends AbstractModule
{
    private final ApplicationConfiguration applicationConfiguration;

    public ApplicationModule(ApplicationConfiguration applicationConfiguration)
    {
        this.applicationConfiguration = applicationConfiguration;
    }

    @Override
    protected void configure()
    {
        bind(ApplicationConfiguration.class).toInstance(applicationConfiguration);

        //todo: temporary
        bind(new TypeLiteral<Class<User>>(){}).toInstance(User.class);
    }

    @Provides
    //todo: hide behind interface
    public CouchDbConnector provideDatastore(/*@Named("database.instance") */CouchDbInstance databaseInstance)
    {
        databaseInstance.deleteDatabase("database"); //todo: temp
        final StdCouchDbConnector database = new StdCouchDbConnector("database", databaseInstance); //todo: to configuration
        database.createDatabaseIfNotExists();
        //todo: as task while application start (configurable)
        return database;
    }

    @Provides
//    @Named("database.instance")
    public CouchDbInstance provideDatabaseInstance(/*@Named("database.http.client") */final HttpClient httpClient)
    {
        return new StdCouchDbInstance(httpClient);
    }

    @Provides
//    @Named("database.http.client")
    public HttpClient provideDatabaseHttpClient() throws MalformedURLException
    {
        return new StdHttpClient.Builder()
                .username("admin")
                .password("password")
                .url("http://localhost:5984") //todo: to configuration
                .build();
    }

//    private Repository createRepository(final Class<? extends CouchDbDocument> clazz, final CouchDbConnector connector)
//    {
//        return new Repository<>(clazz, connector);
//    }
}
