from __future__ import absolute_import

from django.views.generic.list_detail import object_list
from django.contrib.contenttypes.models import ContentType
from django.http import Http404
from django.utils.translation import ugettext as _

from tagtools.tagcloud import *
from tagtools.settings import *

from taggit.models import Tag, TaggedItem

def _get_queryset_and_model(queryset_or_model):
    """
    Given a ``QuerySet`` or a ``Model``, returns a two-tuple of
    (queryset, model).

    If a ``Model`` is given, the ``QuerySet`` returned will be created
    using its default manager.
    """
    try:
        return queryset_or_model, queryset_or_model.model
    except AttributeError:
        return queryset_or_model._default_manager.all(), queryset_or_model

def tagged_object_list(request, queryset_or_model=None, tag=None,
        related_tags=False, related_tag_counts=True, **kwargs):

    if queryset_or_model is None:
        try:
            queryset_or_model = kwargs.pop('queryset_or_model')
        except KeyError:
            raise AttributeError(_('tagged_object_list must be called with a queryset or a model.'))

    if tag is None:
        try:
            tag = kwargs.pop('tag')
        except KeyError:
            raise AttributeError(_('tagged_object_list must be called with a tag.'))

    tag_instance = Tag.objects.get(slug=tag)
    if tag_instance is None:
        raise Http404(_('No Tag found matching "%s".') % tag)

    _, model = _get_queryset_and_model(queryset_or_model)
    ct_model = ContentType.objects.get_for_model(model)
    ti_qs = TaggedItem.objects.filter(content_type=ct_model,
            tag=tag_instance) #.values('tag', 'content_object')
    queryset = model.objects.filter(pk__in=[o.object_id for o in ti_qs])
    if not kwargs.has_key('extra_context'):
        kwargs['extra_context'] = {}
    kwargs['extra_context']['tag'] = tag_instance
#     if related_tags:
#         kwargs['extra_context']['related_tags'] = \
#             Tag.objects.related_for_model(tag_instance, queryset_or_model,
#                                           counts=related_tag_counts)
    return object_list(request, queryset, **kwargs)


