from app.utils.unicode_names import normalize
from app.models.user import User
import re

def valid_name(name, msg=False):
    """
    Checks whether a string is a valid user name. The criteria are:
    1. At least 3 characters and no longer than 32 characters
    2. Only characters allowed in the [unicode_names] utility
    3. At least one letter character (avoid complete garbage)
    4. Not in forbidden user names

    Returns True if the name is valid, otherwise a list of error messages
    that can contain these errors:
      "too-short", "too-long", "cant-normalize", "no-letter", "forbidden"
    Otherwise, returns a bool.
    """

    errors = []

    FORBIDDEN_USERNAMES = ["admin", "root", "webmaster", "contact"]

    # Rule 1
    if len(name) < User.NAME_MINLEN:
        errors.append("too-short")

    if len(name) > User.NAME_MAXLEN:
        errors.append("too-long")

    # Rule 2
    try:
        normalized_name = normalize(name)
    except ValueError:
        normalized_name = None
        errors.append("cant-normalize")

    # Rule 3
    if re.search(r'\w', name) is None:
        errors.append("no-letter")

    # Rule 4
    if normalized_name in FORBIDDEN_USERNAMES:
        errors.append("forbidden")

    return True if errors == [] else errors
