'''
Created on 09 Aout. 2012

@author: Corinne
'''
import logging
import simplejson

from dataparser.ClientDocumentAnnotationDeleteAttributes import ClientDocumentAnnotationDeleteAttributes
from dataparser.ClientDocumentAnnotationCreateAttributes import ClientDocumentAnnotationCreateAttributes
from dataparser.AnnotationsGetAttributes import AnnotationsGetAttributes
from document.models import Document
from django.contrib.auth.models import User
from document.models import Tag
from document.models import Documentaryfile
from document.models import Annotationdocument

logger = logging.getLogger('document')

class DocumentAnnotation(object):

    def __init__(self, request):
        logger.info('DocumentAnnotation init')
        self.request = request
           
    def create(self):
        logger.info('create DocumentAnnotation')
        attr = ClientDocumentAnnotationCreateAttributes(self.request)
        logger.info('get_user = ' + str(attr.get_user()))
        logger.info('get_documentary_file = ' + str(attr.get_documentary_file()))
        logger.info('get_annotation_id = ' + str(attr.get_annotation_id()))
        logger.info('get_document = ' + str(attr.get_document()))
        logger.info('get_tags = ' + str(attr.get_tags()))
        logger.info('get_annotated_text = ' + str(attr.get_annotated_text()))
        logger.info('get_annotated_text_page = ' + str(attr.get_annotated_text_page()))
        logger.info('get_annotated_text_offset = ' + str(attr.get_annotated_text_offset()))

        tags_attr = attr.get_tags()
        try:
            if attr.get_document() == '':
                json = '{"error": "No document_id attribute in the http post request"}'
                logger.info(json)
                return json
                
            document = Document.objects.get(pk=attr.get_document())
            try:
                user_attr = User.objects.get(username=attr.get_user())
                try:
                    if attr.get_documentary_file() == '':
                        json = '{"error": "No documentary_file_id attribute in the http post request" } '
                        logger.info(json)
                        return json
                    documentaryfile = Documentaryfile.objects.get(pk=attr.get_documentary_file())
                except Documentaryfile.DoesNotExist:
                    json = '{"error": "Invalid DocumentaryFile Id"}'
                    logger.info(json)
                    return json
                
                logger.info('documentaryfile.user.name = ' + str(documentaryfile.user.username))
                logger.info('user_attr.name = ' + str(user_attr.username))
                
                if documentaryfile.user.username == user_attr.username:
                    annotationDocument = Annotationdocument(description=attr.get_annotation_id(),user=user_attr, document=document,visibility=documentaryfile.visibility,annoted_text=attr.get_annotated_text(),annoted_text_page=attr.get_annotated_text_page(),annoted_text_offset=attr.get_annotated_text_offset(),documentaryfile=documentaryfile )
                    annotationDocument.save()
                else:
                    json= '{"error": "User does not matched"}'
                    logger.info(json)
            except User.DoesNotExist:
                json= '{"error": "Invalid User Id"}'
                logger.info(json)
                return json
           
            if tags_attr: 
                logger.info('tags associated to annotation')
                for tag in tags_attr:
                    logger.info('annotation_tag = ' + str(tag))
                    tag_attr = Tag(value=tag,annotationdocument=annotationDocument)
                    tag_attr.save()
                                                  
            json= '{"annotation_document_created":'  + str(annotationDocument.id) + '}'
            logger.info(json)
        except Document.DoesNotExist:
            json= '{"error": "Invalid Document Id"}'
            logger.info(json)
            return json
        
        return json

    def delete(self):
        logger.info('delete DocumentAnnotation')
        attr = ClientDocumentAnnotationDeleteAttributes(self.request)
        logger.info('get_user = ' + str(attr.get_user()))
        logger.info('get_annotation_id = ' + str(attr.get_annotation_id()))

        annotationId= attr.get_annotation_id()
        try:
            annotationdocument = Annotationdocument.objects.get(pk=annotationId)
            if attr.get_user() == annotationdocument.user.username:
                annotationdocument.delete()
                json= '{"annotation_document_deleted" :'  + str(annotationId) + '}'
                logger.info(json)
            else:
                json= '{"Error": "User does not matched"}'
                logger.info(json)
        except Annotationdocument.DoesNotExist:
            json= '{"error": "Annotationdocument Id not valid"}'
            logger.info(json)
       
        return json
    
    def get_annotations(self):
        attr = AnnotationsGetAttributes(self.request)
        
        if not attr.get_article():
            json = '{"error msg": "document_id is not defined"}'
            return json
        
        if attr.get_offset()=='' :
            json = '{"error msg": "no offset defined"}'
            return json
        
        if attr.get_count() == '' :
            json = '{"error msg": "no count defined"}'
            return json
        
        json = {}
        json['document_id'] = int(attr.get_article())
        json['offset'] = int(attr.get_offset())
        json['count'] = int(attr.get_count())
        total_count = 0
        json['annotations'] = []
        annotations = Annotationdocument.objects.filter(document_id=attr.get_article())
        for annotation in annotations:
            total_count += 1
            if total_count-1 >= int(attr.get_offset()) and total_count-1 < int(attr.get_offset()) + int(attr.get_count()) :
                jsonannotation = {'id':annotation.id}
                jsonannotation['user'] = annotation.user.username
                jsonannotation['annotated_text'] = annotation.annoted_text
                jsonannotation['annotated_text_page'] = annotation.annoted_text_page
                jsonannotation['annotated_text_offset'] = annotation.annoted_text_offset
                jsonannotation['user_text'] = annotation.description
                
                jsonannotation['tags'] = []
                tags = Tag.objects.filter(annotationdocument_id=annotation.id)

                for tag in tags:
                    jsontag = {'id': tag.value}
                    jsontag = {'title':str(tag.value)}
                    #TO DO URL ?
                    jsonannotation['tags'].append(jsontag)
                    
                json['annotations'].append(jsonannotation)
        json['total_count'] = total_count
        result = simplejson.dumps(json)
        logger.debug(result)
        return result