package com.capgemini.framework.common.activedirectory;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;

/**
 * Helper class to generate filters for Active Directory, e.g. looking for a specific username, etc.
 */
@AllArgsConstructor(access = AccessLevel.PRIVATE)
class SearchFilter {

    private final String value;
    private final SearchCriteria criteria;

    /**
     * Restricts the Search to a user login.
     *
     * @param login the user's login
     * @return a search filter
     */
    public static SearchFilter searchLogin(final String login) {
        return new SearchFilter(login, SearchCriteria.LOGIN);
    }

    /**
     * Restricts the search to a specific Group (such as admin group).
     *
     * @param group the name of the group
     * @return a search filter
     */
    public static SearchFilter searchInGroup(final String group) {
        return new SearchFilter(group, SearchCriteria.GROUP);
    }

    /**
     * Makes a filter component. Various filter components may be chained inside parentheses to construct a powerful filter.<br>
     * For example, a filter component for filtering logins might look like:<br>
     * (cn=THE_LOGIN)
     *
     * @return the filter component
     */
    public String makeFilterComponent() {
        String filterComp;
        switch (criteria) {
            case LOGIN:
                filterComp = "(" + ActiveDirectory.ATTRIBUTES.getLogin() + "=" + value + ")";
                break;
            case GROUP:
                String orgUnitFilter = ActiveDirectory.getOrganisationalUnitBase(ActiveDirectory.ADMINISTRATION.getAdminOU());
                filterComp = "(memberOf=CN=" + value + "," + orgUnitFilter + "," + ActiveDirectory.DOMAIN_CONTROLLER + ")";
                break;
            default:
                filterComp = "";
                break;
        }
        return filterComp;
    }
}
