package repositories;

import database.MongoDBConnector;
import io.dropwizard.auth.basic.BasicCredentials;
import objects.Team;
import objects.User;
import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Optional;

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

    private MongoDBConnector mongoDBConnector;
    private TeamsRepository teamsRepository;
    private MessageDigest messageDigest;

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

//    public Optional<User> get(String username) {
//        Optional<User> userOptional = teamsRepository.getAll()
//                .stream()
//                .map(Team::getMembers)
//                .flatMap(Collection::stream)
//                .filter(user -> user.getName().equals(username))
//                .findFirst();
//        return userOptional;
//    }

    public Optional<User> authenticateUser(BasicCredentials basicCredentials) {
        Optional<User> userOptional = teamsRepository.getAll()
                .stream()
                .map(Team::getMembers)
                .flatMap(Collection::stream)
                .filter(user -> {
                    return user.getName().equals(basicCredentials.getUsername()) &&
                            user.getPassword().equals(
                                    Hex.encodeHexString(messageDigest.digest(basicCredentials.getPassword().getBytes()))); //todo
                })
                .findFirst();
        return userOptional;
    }

//    public void get(UUID uuid) {
//    }

//    public List<User> getAll() {
//        return mongoDBConnector.getCollection("users")
//                .stream()
//                .map((Function<Document, User>) User::new)
//                .collect(Collectors.toList());
//    }

//    public void add(User user) {
//        mongoDBConnector.addDocument("users", new Document(user.toMap()));
//    }

//    public void clean() {
//        mongoDBConnector.removeCollection("users");
//    }
}
