import re
from copy import copy


#this performs a list of checks
def check_list_of_checks(checks,table_info,row):
    msgs=[]
    for ch in checks:
        ( row, m ) = ch(table_info,row)
        msgs=msgs+m
    #formatted version
    msg=""
    inter=""
    for m in msgs:
        msg=msg+inter+m
        if m[0]=="E":
            row=None
        inter="\n"
    return ( row, msgs,msg )


#these functions  will check the row before update/insert, and
#return a (newrow, msgs)
# where msgs is a list of strings , each starting by "W" or "E" (for warning or error)

def extra_spaces(table_info,row):
    msgs=[]
    newrow=copy(row)    
    for j in range(table_info.n_fields):
        f=table_info.fields[j]
        #columninfo=table_info.field_columninfo[f]
        #(Field, Type, Null, Key, Default, Extra) = columninfo
        e=row[j]
        if type(e) == type(""):
            n=re.sub('^[ \t]*','',e)
            n=re.sub('[ \t]*$','',n)
            if n != e:
                msgs.append("W:"+f+": deleted extra spaces")
            newrow[j]=n
            e=n
    return (newrow,msgs)

def empty_null(table_info,row):
    msgs=[]
    newrow=copy(row)    
    for j in range(table_info.n_fields):
        f=table_info.fields[j]
        #FIXME non portable
        columninfo=table_info.field_columninfo[f]
        (Field, Type, Null, Key, Default, Extra) = columninfo
        e=row[j]
        if e != None and e == "" and Null:
            msgs.append("W:"+f+": is empty: converted to NULL")
            newrow[j]=None
    return (newrow,msgs)

def not_null_not_empty(table_info,row):
    msgs=[]
    newrow=copy(row)    
    for j in range(table_info.n_fields):
        f=table_info.fields[j]
        #FIXME non portable
        columninfo=table_info.field_columninfo[f]
        (Field, Type, Null, Key, Default, Extra) = columninfo
        e=row[j]
        if e != None and e == "" and not Null and j != table_info.n_primary:
            msgs.append("E:"+f+": is empty")
    return (newrow,msgs)

