from django.newforms.fields import Field
from django.newforms.util import ValidationError 
from django.contrib.auth.models import User

from django.newforms.widgets import Input

class CommaSeparatedUsersInput(Input):
    input_type = 'text'
    
    def render(self, name, value, attrs=None):

        if value is None:
            value = ''
        elif isinstance(value, (list, tuple)):
            value = (', '.join([ user.username for user in value ]))
        return super(CommaSeparatedUsersInput, self).render(name, value, attrs)

class CommaSeparatedUsersField(Field):
    
    widget = CommaSeparatedUsersInput
    
    def clean(self, value):
        super(CommaSeparatedUsersField, self).clean(value)
        
        if not value:
            return ''
        
        if isinstance(value, (list, tuple)):
            return value

        names = set(value.lower().split(','))
        name_set = set([name.strip().lower() for name in names])
        users = list(User.objects.filter(username__in=name_set))
        unknown_names = name_set ^ set([user.username.lower() for user in users])
        if unknown_names:
            raise ValidationError('this names are incorrect %s ' % str(names))

        return users