import string

from django.contrib.auth.models import User
from django.core.exceptions import ValidationError

from users.models import Player, InviteCode


def username_validator(username):
    if User.objects.filter(username__iexact=username).first() is not None:
        raise ValidationError("Sorry, this username is already in use")

    if len(username) < 3 or len(username) > 16:
        raise ValidationError("Username must be between 3-16 characters long")

    charset = set(string.ascii_letters + string.digits + "_-")
    if not all(x in charset for x in username):
        raise ValidationError("Username may only contain normal letters, numbers and _-")

def username_change_validator(username):
    if len(username) < 3 or len(username) > 16:
        raise ValidationError("Username must be between 3-16 characters long")

    charset = set(string.ascii_letters + string.digits + "_-")
    if not all(x in charset for x in username):
        raise ValidationError("Username may only contain normal letters, numbers and _-")

def invitecode_validator(invitecode):
    if len(invitecode) > 64:
        raise ValidationError("Invite code too long")

    codeObject = InviteCode.objects.filter(code=invitecode).first()

    if not codeObject:
        raise ValidationError("Invite code doesn't exist")

    if not codeObject.active:
        raise ValidationError("Invite code inactive")