from django.conf import settings
from django.conf.urls.defaults import url
from django.core.paginator import Paginator, InvalidPage
from ldt.ldt_utils.models import Segment
from tagging.models import Tag, TaggedItem
from tastypie.http import HttpNotFound
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash


class TagResource(ModelResource):
    class Meta:
        allowed_methods = ['get']
        resource_name = 'tags'
        queryset = Tag.objects.all()
    
    def override_urls(self):
        # WARNING : in tastypie <= 0.9.11, override_urls is used instead of prepend_urls. From 0.9.12, prepend_urls will be prefered and override_urls deprecated
        return [
            url(r"^(?P<resource_name>%s)/search%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_search'), name="api_get_search"),
        ]

    def get_search(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        all_segments = None
        # Search by content ids is priori
        content_ids = request.GET.get('contents', '')
        segment_ids = request.GET.get('segments', '')
        tags_cloud = None
        if content_ids != "":
            # We get all the segments for these contents
            content_ids = content_ids.split(',')
            tags_cloud = Tag.objects.cloud_for_model(Segment, filters={"iri_id__in":content_ids})
        if not all_segments and segment_ids != "":
            segment_ids = segment_ids.split(',')
            tags_cloud = Tag.objects.cloud_for_model(Segment, filters={"element_id__in":segment_ids})
        
        
        limit = request.GET.get('limit', getattr(settings, 'API_LIMIT_PER_PAGE', 20))
        if limit == "0":
            obj_for_bundle = tags_cloud
        else:
            paginator = Paginator(tags_cloud, limit)
            try:
                page = paginator.page(int(request.GET.get('page', 1)))
            except InvalidPage:
                raise HttpNotFound("Sorry, no results on that page.")
            obj_for_bundle = page.object_list
        
        objects = []
        for tag in obj_for_bundle:
            bundle = self.build_bundle(obj=tag, request=request)
            bundle = self.full_dehydrate(bundle)
            objects.append(bundle)

        object_list = {
            'objects': objects,
        }

        self.log_throttled_access(request)
        return self.create_response(request, object_list)