package com.telephoners.krakyournet.ctf.modules;

import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import com.mongodb.MongoClient;
import com.telephoners.krakyournet.ctf.core.ApplicationConfiguration;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ApplicationModule extends AbstractModule
{

    private ApplicationConfiguration applicationConfiguration;

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

    @Override
    protected void configure()
    {
        bind(ApplicationConfiguration.class).toInstance(applicationConfiguration); //todo: refactor

        Morphia morphia = new Morphia();
        morphia.mapPackage("beans.Team"); //todo? what for?
        //todo: instantiate somewhere else?
        Datastore datastore = morphia.createDatastore(
                new MongoClient(applicationConfiguration.getDbHost(), applicationConfiguration.getDbPort()), applicationConfiguration.getDbName());
        datastore.ensureIndexes();
        bind(Datastore.class).toInstance(datastore);
        try {
            bind(MessageDigest.class).annotatedWith(Names.named("messageDigest"))
                    .toInstance(MessageDigest.getInstance(applicationConfiguration.getFlagHashMethod()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
