from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404, get_list_or_404
from django.utils import simplejson
from django.utils.html import escape
from django.utils.translation import ugettext as _
from ldt.ldt_utils.models import Project
from ldt.ldt_utils.projectserializer import ProjectSerializer
import ldt.auth as ldt_auth
from guardian.shortcuts import get_objects_for_user


def project_json_id(request, id): 
    
    project = get_object_or_404(Project.safe_objects, ldt_id=id)

    return project_json(request, project, False)

def project_json_cutting_id(request, id, cutting_id):

    project = get_object_or_404(Project.safe_objects, ldt_id=id)

    return project_json(request, project, first_cutting=cutting_id)

def project_json_externalid(request, id): 
        
    res_proj = get_list_or_404(Project.safe_objects.order_by('-modification_date'), contents__external_id=id) #@UndefinedVariable
    
    return project_json(request, res_proj[0], False)



def project_json(request, project, serialize_contents=True, first_cutting=None):
    
# TODO : the following lines have been commented for tests only
# they should not be commented for production
#    if not ldt_auth.check_access(request.user, project):
#        return HttpResponseForbidden(_("You can not access this project"))
        
    mimetype = request.REQUEST.get("mimetype")
    if mimetype is None:
        mimetype = "application/json; charset=utf-8"
    else:
        mimetype = mimetype.encode("utf-8")
    if "charset" not in mimetype:
        mimetype += "; charset=utf-8" 
    resp = HttpResponse(mimetype=mimetype)
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    
    indent = request.REQUEST.get("indent")
    if indent is None:
        indent = settings.LDT_JSON_DEFAULT_INDENT
    else:
        indent = int(indent)
    
    callback = request.REQUEST.get("callback")
    escape_str = request.REQUEST.get("escape")
    escape_bool = False
    if escape_str:
        escape_bool = {'true': True, 'false': False, "0": False, "1": True}.get(escape_str.lower())
        
    viewable_contents = get_objects_for_user(request.user, 'ldt_utils.view_content', klass=project.contents.all())
        
    ps = ProjectSerializer(project, serialize_contents, viewable_contents=viewable_contents, first_cutting=first_cutting)
    project_dict = ps.serialize_to_cinelab()
    
    json_str = simplejson.dumps(project_dict, ensure_ascii=False, indent=indent)
    
    if callback is not None:
        json_str = "%s(%s)" % (callback, json_str)
    
    if escape_bool:
        json_str = escape(json_str)
    
    resp.write(json_str)

    return resp
