from django.http import Http404
from django.core.urlresolvers import reverse

from staff.groups.models import Group, GROUP_TYPE_CHOICES


def get_group_queryset(type_name=None, type_id=None):
    base_queryset = Group.objects.active()
    if type_name is None and type_id is None:
        return base_queryset
    elif type_name is not None:
        type_id = get_group_type_id_by_type_name(type_name)
    return base_queryset.filter(type=type_id)


def get_group_type_id_by_type_name(type_name):
    return getattr(GROUP_TYPE_CHOICES, type_name.upper())


def get_group_type_name_by_id(type_id):
    return GROUP_TYPE_CHOICES.get_name(type_id).lower()


def get_group_by_id_or_404(id, type_name=None, type_id=None):
    try:
        group = get_group_queryset(type_name, type_id).get(id=id)
        return group
    except Group.DoesNotExist:
        raise Http404


def get_group_by_url_or_404(url, type_name=None, type_id=None):
    try:
        group = get_group_queryset(type_name, type_id).get(url=url)
        return group
    except Group.DoesNotExist:
        raise Http404


def get_group_direct_url(group):
    tree_type = get_group_type_name_by_id(group.type)
    base_url = reverse('groups-tree', kwargs={'tree_type': tree_type})
    hash_part = '#' + group.url
    return base_url + hash_part
