from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.utils.html import escape
from django.template.loader import render_to_string
from ldt.ldt_utils.models import Content, Project, Owner
from ldt.ldt_utils.utils import boolean_convert
from django.http import HttpResponseServerError, HttpResponseForbidden
from django.db.models import Q
import logging
import lxml.etree
from lxml.html import fromstring
import ldt.auth


@login_required
def workspace(request):

    # list of contents
    content_list = Content.objects.all()

    # get list of projects
    project_list = Project.objects.all()

    # render list
    return render_to_response("franceculture/workspace.html", 
                              {'contents': content_list, 'projects': project_list},
                              context_instance=RequestContext(request))

@login_required
def projectsfilter(request, filter, is_owner=False, status=0):
    
    project_list = None
    is_owner = boolean_convert(is_owner)
    status = int(status)
    query = Q()
            
    if is_owner:
        owner = None
        try:
            owner = Owner.objects.get(user=request.user)
        except:
            return HttpResponseServerError("<h1>User not found</h1>")
        query &= Q(owner=owner)
        
    if status > 0:
        query &= Q(state=status)
    
    if filter:
        if len(filter) > 0 and filter[0] == '_':
            filter = filter[1:]
        query &= Q(title__icontains=filter)
    
    project_list =  Project.objects.filter(query)
    
    return render_to_response("franceculture/partial/projectslist.html", 
                              {'projects': project_list},
                              context_instance=RequestContext(request))


@login_required
def contentsfilter(request, filter):
    
    if filter and len(filter) > 0 and filter[0] == '_':
            filter = filter[1:]
    
    if filter:
        content_list = Content.objects.filter(title__icontains=filter)
    else:
        content_list = Content.objects.all()
        
    return render_to_response("franceculture/partial/contentslist.html", 
                              {'contents': content_list},
                              context_instance=RequestContext(request))

     
    
def popup_embed(request):
    
    json_url = request.GET.get("json_url")
    player_id = request.GET.get("player_id")
    ldt_id = request.GET.get("ldt_id")
    
    
    project = Project.objects.get(ldt_id=ldt_id);
    
    if not ldt.auth.checkAccess(request.user, project):
        return HttpResponseForbidden(_("You can not access this project"))

    
    doc = lxml.etree.fromstring(project.ldt)
    
    annotations = []
    
    for contentnode in doc.xpath("/iri/annotations/content"):
        iri_id = contentnode.get("id")
        content = Content.objects.get(iri_id=iri_id)
        
        for annotationnode in contentnode.xpath("ensemble/decoupage/elements/element"):
             
            tags = annotationnode.get('tags')
            tags_list = []
            tags_list.extend(annotationnode.xpath("tags/tag/text()"))
            if tags:
                tags_list.append(tags)
            tags = ",".join(tags_list)
            
            begin = annotationnode.get('begin')
            if begin is None:
                begin = 0
            else:
                begin = int(begin)

            uri = None            
            if content.media_obj.external_publication_url:
                uri = "%s#t=%d" % (content.media_obj.external_publication_url, begin)

            annotations.append({
                'begin': begin,
                'duration':annotationnode.get('dur'),
                'title':u"".join(annotationnode.xpath("title/text()")),
                'desc':u"".join(annotationnode.xpath("abstract/text()")),
                'tags': tags,
                'id':u"".join(annotationnode.get('id')),
                'uri':uri
            })
    
    embed_rendered = dict((typestr,
                           (lambda s:escape(lxml.etree.tostring(fromstring(render_to_string("franceculture/partial/embed_%s.html"%(s), {'json_url':json_url,'player_id':player_id, 'annotations':annotations}, context_instance=RequestContext(request))),pretty_print=True)))(typestr)) 
                           for typestr in ('player','seo_body', 'seo_meta', 'links')  )
    
    return render_to_response("franceculture/embed_popup.html",
                              {'json_url':json_url,'player_id':player_id, 'embed_rendered':embed_rendered, 'annotations':annotations},
                              context_instance=RequestContext(request)) 


