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
from django.db.models import Q


@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:
        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 == "_":
        filter = ""
    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")
    
    
    embed_rendered = escape(render_to_string('franceculture/partial/embed.html', {'json_url':json_url,'player_id':player_id}, context_instance=RequestContext(request)))

    
    return render_to_response("franceculture/embed_popup.html",
                              {'json_url':json_url,'player_id':player_id, 'player_embed_rendered':embed_rendered},
                              context_instance=RequestContext(request)) 
