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;

/**
 * Created by gpietrus on 20.02.2016.
 */
@Singleton
public class UsersRepository implements Repository {

    private Datastore datastore;
    private TeamsRepository teamsRepository;
    private MessageDigest messageDigest;

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

    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() {

    }
}
