from django.core.serializers import json
from django.core.urlresolvers import reverse
from django.utils import simplejson
from ldt.ldt_utils.models import Project
from ldt.ldt_utils.projectserializer import ProjectJsonSerializer
from ldt.ldt_utils.utils import generate_uuid
from tastypie.serializers import Serializer
from tastypie.exceptions import NotFound
import lxml.etree
import logging


class CinelabSerializer(Serializer):
    # Thanks to the this serializer, the api will be able to serialize and deserialize a project in cinelab json format
    # See http://liris.cnrs.fr/advene/cinelab/ for more information
    formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'cinelab']
    content_types = {
        'cinelab': 'application/cinelab',
        'json': 'application/json',
        'jsonp': 'text/javascript',
        'xml': 'application/xml',
        'yaml': 'text/yaml',
        'html': 'text/html',
        'plist': 'application/x-plist',
    }
    json_indent = 2
     
    def to_cinelab(self, data, options=None):
        """
        Given some Python data, produces Cinelab/JSON output.
        N.B. : for the moment, this serializer works with api_dispatch_detail only. 
               It does not work with api_dispatch_list. Only from_cinelab deals with api_dispatch_list's multiple objects like {"objects":[...]}
        """
        options = options or {}
        if hasattr(data, 'obj') :
            if isinstance(data.obj, Project) :
                ps = ProjectJsonSerializer(data.obj)
                data = ps.serialize_to_cinelab()
                return simplejson.dumps(data, cls=json.DjangoJSONEncoder, sort_keys=True, indent=self.json_indent)
        raise NotFound("Project not found")
    

    def from_cinelab(self, content):
        """
        This function takes cinelab/json and transform it into a regular REST API json project data.
        All fields are (* required at rebuilt json) :
        "changed_by": "admin",
        "created_by": "admin",
        "creation_date": "2012-02-11T01:18:48.028534",
        "description": "",
        "image": "/pf/static/media/thumbnails/contents/content_default_icon.png",
        "ldt*": "<iri><project>...<medias>...<annotations>...<displays>...<edits>...</iri>",
        "ldt_id*": "594dc612-544e-11e1-96e5-00145ea49a02",
        "modification_date": "2012-02-11T01:19:40.203322",
        "state": 2,
        "title*": "front project : test DailyMotion"
        "contents": ["IRI_ID_1","IRI_ID_2"]
        """
        logging.debug("FROM cinelab content = " + content)
        
        cinelab = simplejson.loads(content)
        meta = cinelab["meta"]
        ldt_id = generate_uuid()
        contents = [reverse("api_dispatch_detail", kwargs={"api_name":"1.0", "resource_name":"contents", "iri_id":c["id"]}) for c in cinelab["medias"]]
        owner_uri = reverse("api_dispatch_detail", kwargs={"api_name":"1.0", "resource_name":"users", "username":meta["dc:creator"]})
        s = {"description": meta["dc:description"], "ldt_id": "000_GEN_BY_TC3", "title": meta["dc:title"], 
             "created_by": meta["dc:creator"], "changed_by": meta["dc:contributor"], "created_by": meta["dc:creator"], "changed_by": meta["dc:contributor"],
             "contents": contents, "owner": owner_uri}
        
        #s = '{"description": "", "ldt": "<iri><project/><medias/><annotations/><displays/><edits/></iri>", "000ldt_id": "gen_by_tc","title": "aaa GEN BY TC"}'
        #s = '{"description": "", "ldt": "<iri><project/><medias/><annotations/><displays/><edits/></iri>", "title": "aaaGEN BY TC"}'
        return simplejson.loads(simplejson.dumps(s))

        