# -*- coding: utf-8 -*-
# vim: set ts=4

from __future__ import unicode_literals

from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext

from DataTag.models import Media, Tag


def browse(request, path):
    # Parse the 'path' and build the query
    medias = Media.objects.all()
    query_string = ''
    tags = []
    root_tags = []
    non_root_tags = []
    sub_tags = []
    path_elements = [p for p in path.split('/') if p]

    # Show only the selected tags
    for tag_name in path_elements:
        query_string = query_string + '/' + tag_name
        tag = get_object_or_404(Tag, name=tag_name)
        if not tag.is_visible_to(request.user):
            return HttpResponseForbidden()
        tags.append({'obj': tag, 'path': query_string})
        medias = medias.filter(tags=tag)

    for tag in Tag.objects.exclude(pk__in=[tag['obj'].pk for tag in tags]).order_by('-name'):
        if not tag.is_visible_to(request.user):
            continue
        local_medias = medias.filter(tags=tag)
        count = local_medias.count()
        if count:
            if tag.is_root:
                root_tags.insert(0, {'obj': tag, 'count': count,
                                  'path': (query_string + '/' + tag.name),
                                  'thumbnail': local_medias.order_by('?')[0]})
            else:
                non_root_tags.append({'obj': tag, 'count': count,
                                      'path': (query_string + '/' + tag.name),
                                      'thumbnail': local_medias.order_by('?')[0]})
            sub_tags.append({'obj': tag, 'count': count,
                             'path': (query_string + '/' + tag.name),
                             'thumbnail': local_medias.order_by('?')[0]})

    return render_to_response('DataTag/tag/browse.html',
                              {'tags': tags, 'root_tags': root_tags,
                               'non_root_tags': non_root_tags,
                               'sub_tags': sub_tags},
                              context_instance=RequestContext(request))


def details(request, path):
    # TODO: handle OR
    # Check the existence of all tags
    tags = []
    medias = Media.objects.all()
    query_string = ''
    for tag_name in [p for p in path.split('/') if p]:
        query_string = query_string + '/' + tag_name
        tag = get_object_or_404(Tag, name=tag_name)
        if not tag.is_visible_to(request.user):
            return HttpResponseForbidden()
        medias = medias.filter(tags=tag)
        tags.append({'obj': tag, 'path': query_string})

    # TODO: order by dates (from EXIF data)
    medias = medias.order_by('date')

    # Special case for '' path. In this case medias are not filtered
    if path == '':
        medias = [m for m in medias if m.is_visible_to(request.user)]

    return render_to_response('DataTag/tag/details.html',
                              {'medias': medias, 'tags': tags},
                              context_instance=RequestContext(request))

@@ -964,16 +964,43 @@
  tags%5D).
+prefetch_related('groups').
 order_by
@@ -1197,59 +1197,13 @@
     
-if tag.is_root:%0A                root_tags.insert(0,
+obj =
  %7B'o
@@ -1243,39 +1243,24 @@
             
-   
-            
 'path': (que
@@ -1303,39 +1303,24 @@
             
-  
-             
 'thumbnail':
@@ -1342,33 +1342,32 @@
 rder_by('?')%5B0%5D%7D
-)
 %0A            els
@@ -1367,12 +1367,22 @@
     
-else
+if tag.is_root
 :%0A  
@@ -1391,28 +1391,24 @@
             
-non_
 root_tags.ap
@@ -1409,221 +1409,65 @@
 ags.
-append(%7B'obj': tag, 'count': count,%0A                                      'path': (query_string + '/' + tag.name),%0A                                      'thumbnail': local_medias.order_by('?')%5B0%5D%7D)%0A            sub
+insert(0, obj)%0A            else:%0A                non_root
 _tag
@@ -1479,179 +1479,44 @@
 end(
-%7B'
 obj
-': tag, 'count': count,%0A                             'path': (query_string + '/' + tag.name),%0A                             'thumbnail': local_medias.order_by('?')%5B0%5D%7D
+)%0A            sub_tags.append(obj
 )%0A%0A 

Improve performances by removing many SQL queries