from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Q
from django.forms.models import model_to_dict
from django.forms.util import ErrorList
from django.http import (HttpResponse, HttpResponseRedirect,
    HttpResponseForbidden, HttpResponseServerError)
from ldt.indexation import get_results_with_context, highlight_documents
from django.shortcuts import (render_to_response, get_object_or_404,
    get_list_or_404)
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils import simplejson
from django.utils.html import escape
from django.utils.translation import ugettext as _, ungettext
from ldt.ldt_utils.forms import (LdtAddForm, SearchForm, AddProjectForm, CopyProjectForm,
    ContentForm, MediaForm, GroupAddForm)
from guardian.shortcuts import remove_perm, get_objects_for_group, get_objects_for_user
from ldt.ldt_utils.models import Content, Media, Project
from ldt.ldt_utils.utils import boolean_convert, LdtUtils, LdtSearch
from ldt.security.utils import (assign_perm_to_obj, set_forbidden_stream, 
    add_change_attr, get_userlist, get_userlist_model, get_userlist_group)
from ldt.security.cache import get_cached_checker, cached_assign
from lxml.html import fragment_fromstring
#from models import Media, Project
from ldt.ldt_utils.projectserializer import ProjectSerializer
from urllib2 import urlparse
from operator import itemgetter
from itertools import groupby
import base64
import django.core.urlresolvers
import ldt.auth as ldt_auth
import ldt.utils.path as ldt_utils_path
import logging
import lxml.etree
import mimetypes
import os
import urllib2
import subprocess
import re
import datetime


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_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): # Not checked
    
    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())
        
        
    ps = ProjectSerializer(project, serialize_contents)
    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
