package com.telephoners.krakyournet.ctf.modules;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.name.Named;
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;

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);
    }

    @Provides
    public CouchDbConnector provideDatastore(@Named("database.instance") CouchDbInstance databaseInstance)
    {
        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()
                .url("http://localhost:5984") //todo: to configuration
                .build();
    }

}
