from tagging import settings
import re

multi_space = re.compile("[\s_]+", re.U)

def get_tag_name_list(string, space=' '):
    return [ multi_space.sub(space, name.strip())
                for name in string.split(',') if name and not name.isspace() ]

def tags2str(tagset):
    return tagnames2str(t.name for t in tagset)
    
def tagnames2str(names):
    return u', '.join(sorted(set(multi_space.sub(' ', name.strip())
                                 for name in names 
                                 if name and not name.isspace())))

def clean(string):
    if string is None: return u''
    if not isinstance(string, (str, unicode)):
        string = ','.join(string)
    res = u', '.join(sorted(set(multi_space.sub(' ', name.strip())
                      for name in string.split(',') 
                      if name and not name.isspace())))
    if settings.FORCE_LOWERCASE_TAGS: return res.lower()
    return res
