package repositories;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.dropwizard.auth.basic.BasicCredentials;
import objects.User;
import org.apache.commons.codec.binary.Hex;
import org.mongodb.morphia.Datastore;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Singleton
public class UsersRepository implements Repository
{
    private Datastore datastore;
    private MessageDigest messageDigest;

    @Inject
    public UsersRepository(Datastore datastore)
    {
        this.datastore = datastore;
        try {
            messageDigest = MessageDigest.getInstance("MD5"); //todo
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public void add(User user)
    {
        datastore.save(user);
    }

    public User getUserByName(String username)
    {
        return datastore.createQuery(User.class)
                .field("name").equal(username)
                .get();
    }

    public User authenticateUser(BasicCredentials basicCredentials)
    {
        return datastore.createQuery(User.class)
                .field("name").equal(basicCredentials.getUsername())
                .field("password").equal(Hex.encodeHexString(messageDigest.digest(basicCredentials.getPassword().getBytes())))
                .get();
    }

    @Override
    public List getAll()
    {
        return null;
    }

    @Override
    public void initialize()
    {

    }
}
