'''
Created on 7 aout 2012

@author: gerard
'''
import logging
import simplejson

from dataparser.ClustersGetAttributes import ClustersGetAttributes
from document.models import Annotationcluster
from document.models import Cluster
from document.models import Clusterdocumentweight
from document.models import Document
from document.models import Documentaryfile
from django.contrib.auth.models import User
from mediapartdb.MediapartReader import MediapartReader

logger = logging.getLogger('document')

# List of documents of a cluster with annotations
class Clusters(object):

    def __init__(self, request):
        self.request = request
    
    def get_treemap_of_clusters(self):
        attr = ClustersGetAttributes(self.request)
        
        if not attr.get_user():
            json = '{"error msg": "user is not defined"}'
            return json
        if not attr.get_documentary_file_id():
            json = '{"error msg": "documentary_file_id is not defined"}'
            return json
        
        the_user = User.objects.get(username=attr.get_user())
        
        if the_user:
            docFiles = Documentaryfile.objects.filter(id=int(attr.get_documentary_file_id()), user_id=the_user.id )
            if len(docFiles) == 0:
                json = '{"error msg": "There is no documentary file belonging to the user specified"}'
                return json
        
        reader = MediapartReader()
        
        json = {"clusters":[]}
        clusters = Cluster.objects.filter(documentaryfile=int(attr.get_documentary_file_id()))
        for cluster in clusters:
            jsoncluster = {'id':cluster.id}
            jsoncluster['title'] = cluster.title
            jsoncluster['abstract'] = cluster.description
            jsoncluster['weight'] = cluster.weight
            
            jsoncluster['annotations'] = []
            
            annotations = Annotationcluster.objects.filter(cluster=cluster.id)
            for annotation in annotations:
                jsonanno = {'id':annotation.id}
                jsonanno['user'] = str(annotation.user)
                jsonanno['text'] = str(annotation.description)
                jsoncluster['annotations'].append(jsonanno)
             
            jsoncluster['documents'] = []
            
            doc_weights = Clusterdocumentweight.objects.filter(cluster_id=cluster.id)
            sorted_doc_weights = sorted(doc_weights, key=lambda a_cluster_doc_weight: a_cluster_doc_weight.weight)
            
            for index_doc, doc_weights in enumerate(sorted_doc_weights):
                if index_doc < 3:
                    jsondoc = {'id':doc_weights.document.documentId}
                    doc = Document.objects.get(documentId=doc_weights.document.documentId)
                    jsondoc['title'] = str(doc.title.encode("utf8"))
                    url = reader.get_url(str(doc_weights.document.documentId))
                    jsondoc['url_document'] = url
                    jsondoc['date'] = str(doc.date.isoformat())
                    category = reader.get_category(str(doc_weights.document.documentId))
                    jsondoc['category'] = category
                    jsondoc['url_image'] = 'TO BE DEFINED'
                    jsondoc['weight'] = float(doc_weights.weight)
    
                    jsoncluster['documents'].append(jsondoc)
                else:
                    break
            jsoncluster['document_number'] = len(sorted_doc_weights)
            json['clusters'].append(jsoncluster)
        
        result = simplejson.dumps(json)
        logger.debug(result)
        return result  
