package com.telephoners.krakyournet.ctf.repositories;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.telephoners.krakyournet.ctf.beans.User;
import com.telephoners.krakyournet.ctf.exceptions.UserNotFoundException;
import com.telephoners.krakyournet.ctf.providers.MessageDigestProvider;
import io.dropwizard.auth.basic.BasicCredentials;
import org.apache.commons.codec.binary.Hex;
import org.mongodb.morphia.Datastore;

@Singleton
public class UsersRepository extends Repository<User>
{
    private final MessageDigestProvider messageDigestProvider;

    @Inject
    public UsersRepository(Datastore datastore, MessageDigestProvider messageDigestProvider)
    {
        super(datastore);
        this.messageDigestProvider = messageDigestProvider;
    }

    public User getUserByName(String username)
    {
        return datastore.createQuery(User.class)
                .field("name").equal(username)
                .asList()
                .stream()
                .findFirst()
                .orElseThrow(UserNotFoundException::new);
    }

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