from django.core.serializers import json
from django.utils import simplejson
from ldt.ldt_utils.models import Project
from ldt.ldt_utils.projectserializer import ProjectJsonSerializer
from tastypie.serializers import Serializer
from tastypie.exceptions import NotFound
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 JSON output.
        """
        logging.debug("TO cinelab data " + repr(data))
        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.
        """
        logging.debug("FROM cinelab content = " + content)
        #a = simplejson.loads(content)
        logging.debug("msg")
        return simplejson.loads(content)