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_annotations_rdf(request, ldt_id):

    project = Project.safe_objects.get(ldt_id=ldt_id); #@UndefinedVariable
    
    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/rdf+xml; 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'

    ps = ProjectSerializer(project, from_contents=False, from_display=True) 
    annotations = ps.get_annotations(first_cutting=True)
    
    rdf_ns = u"http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    dc_ns = u"http://purl.org/dc/elements/1.1/"
    rdf = u"{%s}" % rdf_ns
    dc = u"{%s}" % dc_ns
    nsmap = {u'rdf' : rdf_ns, u'dc':dc_ns}
    
    rdf_root = lxml.etree.Element(rdf + u"RDF", nsmap=nsmap)
    
    logging.debug("RDF annotations : " + repr(annotations)) #@UndefinedVariable
    
    for annotation in annotations:
        uri = u""
        if 'uri' in annotation and annotation['uri']:
            uri = unicode(annotation['uri'])
        annot_desc = lxml.etree.SubElement(rdf_root, rdf + u"Description")
        annot_desc.set(rdf + u'about', uri)
        if annotation['title']:
            lxml.etree.SubElement(annot_desc, dc + 'title').text = lxml.etree.CDATA(unicode(annotation['title']))
        if annotation['desc']:
            lxml.etree.SubElement(annot_desc, dc + 'description').text = lxml.etree.CDATA(unicode(annotation['desc']))
        if annotation['tags']:
            for tag in annotation['tags']:
                lxml.etree.SubElement(annot_desc, dc + 'subject').text = lxml.etree.CDATA(unicode(tag))
        lxml.etree.SubElement(annot_desc, dc + 'coverage').text = u"start=%s, duration=%s" % (annotation['begin'], annotation['duration'])
        
    resp.write(u"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
    resp.write(u"<!DOCTYPE rdf:RDF PUBLIC \"-//DUBLIN CORE//DCMES DTD 2002/07/31//EN\" \"http://dublincore.org/documents/2002/07/31/dcmes-xml/dcmes-xml-dtd.dtd\">\n")
    
    resp.write(lxml.etree.tostring(rdf_root, xml_declaration=False, encoding="utf-8", pretty_print=True))

    return resp