import mimetypes
from itertools import count
import datetime


from django.utils import timezone
from django.contrib.auth.models import User


def clean_ldap_user(user):
    '''Clean references to module in django-auth-ldap User model, allowing
       pickling of the instances.'''
    user.ldap_user = None
    return user

def match_mime_type(t1, t2):
    if t1.endswith('/*') or t2.endswith('/*'):
        t1 = t1.split('/')[0]
        t2 = t2.split('/')[0]
    if '*' in (t1, t2):
        return True
    return t1 == t2


def match_mime_types(mime_type, mime_types):
    for other_mime_type in mime_types:
        if match_mime_type(other_mime_type, mime_type):
            return True
    return False


def file_match_mime_types(file_like, mime_types):
    import magic

    if not mime_types:
        return True
    mime_type = magic.from_buffer(file_like.read(), mime=True)
    return match_mime_types(mime_type, mime_types)


def mime_types_to_extensions(mime_types):
    extensions = set()
    for mime_type in mime_types:
        extension = mimetypes.guess_extension(mime_type, strict=False)
        if extension is None:
            continue
        extensions.add(extension)
    return sorted(extensions)


def get_free_delegation_number(user):
    '''Allocate a new delegation username'''
    for i in count(1):
        delegate_username = user.username + '-%d' % i
        try:
            User.objects.get(username=delegate_username)
        except User.DoesNotExist:
            return delegate_username

from django.utils.http import int_to_base36
from django.contrib.auth.tokens import default_token_generator
from django.core.urlresolvers import reverse

def make_password_reset_url(request, user):
    uid = int_to_base36(user.id)
    token = default_token_generator.make_token(user)
    return request.build_absolute_uri(
            reverse('auth_password_reset_confirm',
            kwargs={'uidb36': uid, 'token': token}))

def date_to_aware_datetime(date):
    return timezone.make_aware(
            datetime.datetime(date.year, date.month, date.day),
            timezone.get_current_timezone())

def queryset_fixpoint(initial, qs_function):
    initial = set(initial)
    count = len(initial)
    while True:
        initial |= set(qs_function(initial))
        if len(initial) == count:
            break
        count = len(initial)
    return initial
