package lc.esp.engine;

import lc.mecha.aaa.ActiveDirectory;

import javax.naming.NamingException;
import java.util.Map;
import java.util.Set;

/**
 * This class implements the mk16 directory-service API. It provides a simplified shim for working with a
 * Directory service implementation.
 *
 * @author Alex Leigh
 * @since mk19
 */
public class Directory {
    private final ActiveDirectory ad;

    public Directory(ActiveDirectory ad) {
        this.ad = ad;
    }

    /**
     * Authenticate the given username & password in the directory. If the authentication is successful, the userId
     * for the principal is returned. In the context of ActiveDirectory this is the SID.
     */
    public String authenticate(String username, String password) {
        Map res = ad.authenticate(username, password);
        if (res == null) return null;
        return (String) res.get("objectSid");
    }

    public String findUser(String username) throws NamingException {
        Set<Map> users = ad.findUser(username);
        if (users.size() == 0) return null;
        if (users.size() > 1) throw new NamingException();
        // What a dumb fucking interface. Thanks Java.
        for (Map user : users) {
            return (String) user.get("objectSid");
        }

        // Should never reach this.
        return null;
    }

    public void updatePassword(String userId, String newPassword) throws Exception {
        ad.updatePassword(userId, newPassword);
    }

    public Set<String> findGroups(String userId) throws NamingException {
        return ad.findGroups(userId);
    }

}
