from django.conf import settings
from django.conf.urls.defaults import url
from django.core.paginator import Paginator, InvalidPage
from django.db.models import F, Q
from ldt.indexation import get_results_with_context
from ldt.ldt_utils.models import Content, Segment
from ldt.ldt_utils.segmentserializer import SegmentSerializer
from tastypie.constants import ALL
from tastypie.http import HttpNotFound
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash


class SegmentResource(ModelResource):
    class Meta:
        allowed_methods = ['get']
        resource_name = 'segments'
        excludes = ['project_obj', 'content']
        queryset = Segment.objects.all()
        filtering = {
            'iri_id': ALL,
            'start_ts': ALL,
        }
    
#    # WARNING : this segment API will only return json format, no matter format get parameter.
#    def determine_format(self, request):
#        return "application/json"
    
    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"),
            url(r"^(?P<resource_name>%s)/bytimecode%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_segments_by_timecode'), name='segment_api_empty'),
            url(r"^(?P<resource_name>%s)/bytimecode/(?P<iri_id>.*)/(?P<begin>.*)/(?P<end>.*)$" % self._meta.resource_name, self.wrap_view('get_segments_by_timecode'), name='segment_api'),
        ]

    def get_search(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        # Do the query.
        search = request.GET.get('q', '')
        field = "all"
        content_list = None
        if u'author:' in search.lower() :
            sub = search[7:]
            sub = sub.upper()
            if sub[0] != u'"':
                sub = u'"' + sub
            if sub[-1] != u'"':
                sub = sub + u'"'
            search = u'author:' + sub
        results = get_results_with_context(field, search, content_list)
        all_segments = Segment.objects.filter(element_id__in=[e['element_id'] for e in results])
        paginator = Paginator(all_segments, getattr(settings, 'API_LIMIT_PER_PAGE', 20))

        try:
            page = paginator.page(int(request.GET.get('page', 1)))
        except InvalidPage:
            raise HttpNotFound("Sorry, no results on that page.")

        objects = []

        for segment in page.object_list:
            bundle = self.build_bundle(obj=segment, 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 get_segments_by_timecode(self, request, api_name, resource_name, iri_id=None, begin=None, end=None):
        """
        returns segments about content iri_id between timecodes begin and end
        """
        if not begin:
            return HttpNotFound("begin timecode argument is missing.")
        if not end:
            return HttpNotFound("end timecode argument is missing.")
        begin = int(begin)
        end = int(end)
        
        content = Content.objects.filter(iri_id=iri_id)
        if not content:
            return HttpNotFound("Content does not exist or id is not correct.")
        content = content[0]
        
        segments = Segment.objects.filter(content=content).filter(
                    Q(start_ts__gte=begin, start_ts__lte=end) |                            # segment starts between begin and end
                    Q(start_ts__gte=begin-F('duration'), start_ts__lte=end-F('duration')) |# segment ends between begin and end
                    Q(start_ts__lte=begin, start_ts__gte=end-F('duration'))                # period [begin:end] is included in the segment
                    )
        
        a = SegmentSerializer(content, segments)
        return self.create_response(request, a.serialize_to_cinelab())
    