from django.conf import settings
from django.conf.urls import url
from django.core.paginator import Paginator, InvalidPage
from ldt.ldt_utils.models import Segment
from ldt.templatetags.taggit_extras_ldt import get_queryset
from taggit.models import Tag
from tastypie.http import HttpNotFound
from tastypie.resources import ModelResource, ALL
from tastypie.utils import trailing_slash


class TagResource(ModelResource):
    class Meta:
        allowed_methods = ['get']
        resource_name = 'tags'
        queryset = Tag.objects.all()
        filtering = {
            'name': ALL,
        }
        ordering = ["name"]
        # exact, iexact, contains, icontains, in, gt, lt, startswith, istartswith, endswith, iendswith, search, regexp, iregexp
    
    def prepend_urls(self):
        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', '')
        # We define the number of steps in weight int
        try:
            weight_steps = int(request.GET.get('steps', 10))
        except:
            weight_steps = 10
        tags_cloud = None
        if content_ids=="all" or segment_ids=="all":
            #tags_cloud = Tag.objects.cloud_for_model(Segment, steps=weight_steps)
            tags_cloud = get_queryset('ldt_utils.Segment')
        elif 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}, steps=weight_steps)
            tags_cloud = get_queryset(Segment.objects.filter(iri_id__in=content_ids))
        elif 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}, steps=weight_steps)
            tags_cloud = get_queryset(Segment.objects.filter(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)
    
    def dehydrate(self, bundle):
        # This function enable to add the weight of a tag in the bundle's datas, which is not in the tag model
        if bundle.obj and hasattr(bundle.obj,'font_size'):
            bundle.data['weight'] = bundle.obj.font_size
        if bundle.obj and hasattr(bundle.obj,'num_times'):
            bundle.data['weight'] = bundle.obj.num_times
        return bundle