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.beans.tasks.Task;
import io.dropwizard.auth.basic.BasicCredentials;
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 extends Repository<User>
{
    private MessageDigest messageDigest;

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

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

    @Override
    public void clean()
    {
        datastore.getCollection(User.class).drop();
    }

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