import fnmatch
import re


def build_names_list(names_list,column_names_list,regex=True,matching=True):
    """
    Returns a list of names among those provided in `names_list` matching the names in `column_names_list`
        * If `matching` is True, then all the names in `column_names_list`  that matches at least one  name names_list are returned in the output list
        * If `matching` is False, then all the names in `column_names_list`  that do not match any name in names_list are returned in the output list
        * If `regex` is True, then the matching is done according tu usual regular expression syntax



    Parameters
    ----------
    names_list : list of strings
        the list of names/regexp to match against the `column_names_list`
    column_names_list : list of strings
        the list of column names
    regex : bool
    skip  : bool

    Returns
    -------
    selected_names_list : list of strings
        the list of selected column names

    """

    if type(names_list) != list:
        names_list = list([names_list])

    if matching==True:
        selected_names_list=[]
    else:
        selected_names_list=column_names_list[:]

    if regex==True:
        for use_name in names_list:
            regex = fnmatch.translate(use_name)
            matches = [name for name in column_names_list if re.match(regex, name)]
            #print ('matches',regex,matches)
            for match in matches:
                if matching==True:
                    if match not in selected_names_list:
                        selected_names_list.append(match)
                else:
                    if match  in selected_names_list:
                        #print ("removing",match)
                        selected_names_list.remove(match)
    else:
        for ID,name in enumerate(column_names_list):
            if name  in names_list:
                if matching==True:
                    selected_names_list.append(name)
                else :
                    selected_names_list.remove(name)

    return selected_names_list