import logging


def build_filter_dict(filter_states, batch_id, filter_dict, sacred_id=None):
    """
    Construct a dictionary to be used for filtering a MongoDB collection.

    Parameters
    ----------
    filter_states: list
        The states to filter for, e.g. ["RUNNING", "PENDING"].
    batch_id: int
        The batch ID to filter.
    filter_dict: dict
        The filter dict passed via the command line. Values in here take precedence over values passed via
        batch_id or filter_states.
    sacred_id: int
        Sacred ID (_id in the database collection) of the experiment. Takes precedence over other filters.

    Returns
    -------
    filter_dict: dict
    """

    if sacred_id is not None:
        return {'_id': sacred_id}

    if filter_dict is None:
        filter_dict = {}

    if filter_states is not None and len(filter_states) > 0:
        if 'status' not in filter_dict:
            filter_dict['status'] = {'$in': filter_states}
        else:
            logging.warning(f"'status' was defined in the filter dictionary passed via the command line (-f): "
                            f"{filter_dict['status']} AND --status was set to {filter_states}. "
                            f"I'm using the value passed via -f.")

    if batch_id is not None:
        if 'batch_id' not in filter_dict:
            filter_dict['batch_id'] = batch_id
        else:
            logging.warning(f"'batch_id' was defined in the filter dictionary passed via the command line (-f): "
                            f"{filter_dict['status']} AND --batch-id was set to {filter_states}. "
                            f"I'm using the value passed via -f.")
    return filter_dict