from ldt.ldt_utils.models import Project, Content
from ldt.ldt_utils.stat import add_annotation_to_stat
from ldt.ldt_utils.utils import LdtAnnotation
from ldt.security import protect_models, unprotect_models
from tastypie import fields
from tastypie.authorization import Authorization
from tastypie.exceptions import NotFound, BadRequest
from tastypie.resources import Resource
import logging #@UnresolvedImport


class AnnotationObject(object):
    # For the moment, these attributes are useless. We just need to define AnnotationObject
    id = ""
    project = ""
    type = ""
    type_title = ""
    media = ""
    begin = ""
    end = "" 
    content = {"data":""}
    tags = []
    meta = {"creator":"","created":""}
    
class AnnotationResource(Resource):
    # For the moment, these attributes are useless. We just prepare relations to AnnotationObject
    id = fields.CharField(attribute = 'id')
    project = fields.CharField(attribute = 'project')
    type = fields.CharField(attribute = 'type')
    type_title = fields.CharField(attribute = 'type_title')
    media = fields.CharField(attribute = 'media')
    begin = fields.IntegerField(attribute = 'begin')
    end = fields.IntegerField(attribute = 'end')
    content = fields.DictField(attribute = 'content')
    tags = fields.ListField(attribute = 'tags')
    meta = fields.DictField(attribute = 'meta')
    
    class Meta:
        allowed_methods = ['put']
        resource_name = 'annotations'
        object_class = AnnotationObject
        authorization = Authorization()
        # always_return_data = True because we want the api returns the data with the updated ids
        always_return_data = True
    
    def obj_delete_list(self, request=None, **kwargs):
        return True
    
    def obj_create(self, bundle, request=None, **kwargs):
        """
        """
        logging.debug("ICI 0-1 bundle.data = " + repr(bundle.data))
        project_id = ""
        if bundle.data.has_key('project') :
            project_id = bundle.data["project"]
        if project_id and project_id != "" :
            try:
                project = Project.objects.get(ldt_id=project_id)
            except Project.DoesNotExist:
                raise NotFound("Project not found. project_id = " + project_id)
        else :
            # If the project's is not defined, we get or create the content's front project.
            iri_id = bundle.data["media"]
            try:
                content = Content.objects.get(iri_id=iri_id)
            except Content.DoesNotExist:
                raise NotFound("Content not found. iri_id = " + iri_id)
            project = content.get_or_create_front_project()
            bundle.data["project"] = project.ldt_id
        
        adder = LdtAnnotation(project)
        unprotect_models() # Allows anonymous user to modify models in this request only
        # Here the bundle.data has the datas for only one annotation. The others api's functions parse the "objects" from the request's json.
        a = bundle.data
        dur = str(a['end'] - a['begin'])
        begin = str(a['begin'])
        # We test if the annotation has audio node
        audio_src = ""
        audio_href = ""
        if a['content'].has_key('audio') :
            if a['content']['audio'].has_key('src') :
                audio_src = a['content']['audio']['src']
            if a['content']['audio'].has_key('href') :
                audio_href = a['content']['audio']['href']
        meta = a['meta']
        author = meta['creator']
        date = meta['created']
        type_id, new_id = adder.add(a['media'], a['type'], a['type_title'], a['content']['data'], '', a['tags'], begin, dur, author, date, None, "2194379", audio_src, audio_href)
        if not new_id:
            protect_models()
            raise BadRequest
                        
        content = project.contents.get(iri_id=a['media'])
        add_annotation_to_stat(content, a['begin'], a['end'])
        
        # We update the ids
        bundle.data['type'] = type_id
        bundle.data['id'] = new_id
        if not bundle.data['content'].has_key('audio') :
            bundle.data['content']['audio'] = {'src':audio_src, 'href':audio_href}
        # We reinject the datas in the bundle's response
        bundle = self.full_hydrate(bundle)
            
        # We save the added annotation and reprotect the contents and projects
        adder.save()
        protect_models()
        return bundle

    