from django.conf.urls.defaults import url
from ldt.ldt_utils.models import Content
from tastypie.resources import Bundle, ModelResource
from tastypie import fields
from ldt.indexation import get_results_list
from itertools import groupby

        
class ContentResource(ModelResource):
    
    front_project = fields.ForeignKey('ldt.api.ldt.resources.ProjectResource','front_project', null=True, full=False)
    
    class Meta:
        allowed_methods = ['get']
        resource_name = 'contents'
        queryset = Content.objects.select_related('front_project').all()
        excludes = ['media_obj']
    
    def get_object_list(self, request):
        return Content.safe_objects.all()

    def override_urls(self):
        # WARNING : in tastypie <= 1.0, override_urls is used instead of prepend_urls. From 1.0.0, prepend_urls will be prefered and override_urls deprecated 
        return [
            url(r"^(?P<resource_name>%s)/recommended/$" % self._meta.resource_name, self.wrap_view('get_recommended'), name="api_contents_recommended"),
            url(r"^(?P<resource_name>%s)/(?P<iri_id>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),            
        ]
    def get_resource_uri(self, bundle_or_obj):
        kwargs = {
            'resource_name': self._meta.resource_name,
            'api_name': self._meta.api_name
        }
        if isinstance(bundle_or_obj, Bundle):
            kwargs['iri_id'] = bundle_or_obj.obj.iri_id
        else:
            kwargs['iri_id'] = bundle_or_obj.iri_id
        return self._build_reverse_url("api_dispatch_detail", kwargs=kwargs)
    
    def get_recommended(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        
        keywords = request.GET.get('keywords','')
        keywords_search = " OR ".join(keywords.split(','))
        field = request.GET.get('field','all')
        
        result_list = get_results_list(field, keywords_search)
        score_dict = dict([(k,sum([e.score for e in i])) for k,i in groupby(result_list, lambda e: e.iri_id)])
        
        res = [self.full_dehydrate(self.build_bundle(obj=c, request=request)) for c in Content.safe_objects.filter(iri_id__in = score_dict.keys())]

        def add_score(b,s):
            b.data['score'] = s
            return b

        object_list = {
            'objects': sorted([add_score(b, score_dict.get(b.data['iri_id'],0)) for b in res], key=lambda b: b.data['score'], reverse=True),
        }

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