from flask_login import current_user
from wtforms.validators import ValidationError
from app.models.users import User, Member

def name(form, name):
    member = Member.query.filter_by(name=name.data).first()
    if member is not None:
        raise ValidationError('Pseudo indisponible.')
    if not User.valid_name(name.data):
        raise ValidationError("Nom d'utilisateur invalide.")

def email(form, email):
    member = Member.query.filter_by(email=email.data).first()
    if member is not None:
        raise ValidationError('Adresse email déjà utilisée.')

def password(form, password):
    if len(password.data) != 0 and len(password.data) < 10:
        raise ValidationError('Mot de passe est trop court (10 caractères minimum).')
        # TODO: add more rules >:]

def avatar(form, avatar):
    pass

def old_password(form, field):
    if field.data:
        if not form.old_password.data:
            raise ValidationError('Votre ancien mot de passe est requis pour cette modification.')
        if not current_user.check_password(form.old_password.data):
            raise ValidationError('Mot de passe actuel erroné.')
