'''
Created on 27 juil. 2012

@author: gerard
'''
import datetime
import logging

from time import  mktime 
from django.core.cache import cache

from dataparser.ClientDocumentaryFileAttributes import ClientDocumentaryFileAttributes
from dataparser.ClientDocumentaryFileVisibilityAttributes import ClientDocumentaryFileVisibilityAttribute
from dataparser.ClientDocumentaryFileDeleteAttributes import ClientDocumentaryFileDeleteAttributes
from document.models import Cluster
from document.models import Image
from document.models import Document
from document.models import Documentaryfile
from document.models import Clusterdocumentweight
from django.contrib.auth.models import User

logger = logging.getLogger('document')

class DocumentaryFile(object):

    def __init__(self, request):
        logger.info('DocumentaryFile init')
        self.request = request
           
    def create(self):
        logger.info('create DocumentaryFile')
        attr = ClientDocumentaryFileAttributes(self.request)
        logger.info('user = ' + str(attr.get_user()))
        logger.info('query_id = ' + str(attr.get_query_id()))
        logger.info('public = ' + str(attr.get_visibility()))
        query_id = attr.get_query_id()   
        print query_id   
        key1 = cache.get(query_id)
        if key1:
            context = cache.get(key1['weblab_data_key'])
            if context == None:
                print "cache empty"
                json = '{"Error": "Invalid query id"}'
                logger.info(json)
            else:
                print "cache not empty"
                list_concepts,concepts_with_detailed_documents_list = context
                logger.info('list_concepts' + str(list_concepts))
                logger.info('concepts_with_detailed_documents_list' + str(concepts_with_detailed_documents_list))
                #parse to get the value to save the documentary file
                json = self.parseAndSaveValue(list_concepts,concepts_with_detailed_documents_list, attr )
        else:
            json = '{"Error": "Invalid query id"}'
            logger.info(json)
        return json
    
    def visibilityChange(self):
        logger.info('visibilityChange')
        attr = ClientDocumentaryFileVisibilityAttribute(self.request)
        logger.info('get_user = ' + str(attr.get_user()))
        logger.info('get_documentary_file_id = ' + str(attr.get_documentary_file_id()))
        logger.info('get_visibility = ' + str(attr.get_visibility()))
        try:
            documentaryfile = Documentaryfile.objects.get(pk=attr.get_documentary_file_id())
        except Documentaryfile.DoesNotExist:
            json = '{"Error": "Invalid documentary id"}'
            logger.info(json)
            return json
        
        logger.info('documentaryfile.user.name = ' + str(documentaryfile.user.username))
        if documentaryfile.user.username == attr.get_user():
            if attr.get_visibility() == 'public':
                visibility_attr = True
            elif attr.get_visibility() == 'private':
                visibility_attr = False
            else:
                json = '{"Error" : "Invalid visibility parameter"}'
                logger.info(json)
                return json
            
            for thecluster in documentaryfile.cluster_set.all():
                for thedocument in thecluster.document.all():
                    for theannotationdoc in thedocument.annotationdocument_set.all():
                        theannotationdoc.visibility = visibility_attr
                        theannotationdoc.save()
                       
            documentaryfile.visibility = visibility_attr
            documentaryfile.save()
            json = '{"visibility": "' + attr.get_visibility() + '"}'
            logger.info(json)
        else:
            json = '{"Error": "User does not matched"}'
            logger.info(json)
       
        return json
        
    def delete(self):
        logger.info('delete DocumentaryFile')
        attr = ClientDocumentaryFileDeleteAttributes(self.request)
        logger.info('get_user = ' + str(attr.get_user()))
        logger.info('get_documentary_file_id = ' + str(attr.get_documentary_file_id()))
        docId = attr.get_documentary_file_id()
        if docId == '':
            json= '{"Error": "No documentary_file_id attribute in the http post request"}'
            logger.info(json)
            return json
        
        try:
            documentaryfile = Documentaryfile.objects.get(pk=attr.get_documentary_file_id())
        except Documentaryfile.DoesNotExist:
            json= '{"Error": "Invalid documentary_file_id"}'
            logger.info(json)
            return json
        
        logger.info('documentaryfile.user.username = ' + str(documentaryfile.user.username))
        if documentaryfile.user.username == attr.get_user():
            #verify if the associated documents are associated to another documentaryfile. if not delete the documents
            for thecluster in documentaryfile.cluster_set.all():     
                for thedocument in thecluster.document.all():
                    nb = (Clusterdocumentweight.objects.filter(document_id=thedocument.documentId)).count()
                    logger.info('nb' + str(nb))
                    if nb == 1:
                        thedocument.delete()
           
            documentaryfile.delete()
            json = '{"documentary_file_deleted" :' + str(docId) + '}'
            logger.info(json)
        else:
            json= '{"Error": "User does not match"}'
            logger.info(json)
       
        return json  
    
    def parseAndSaveValue(self, list_concepts,concepts_with_detailed_documents_list, attr):
        #parse the context

        try:
            user_attr = User.objects.get(username=attr.get_user)
        except User.DoesNotExist, err:
            logger.info(' Error: '+ str(err))
            json = '{"Error": "User does not existed"}' 
            return json
        
        visibility_attr = attr.get_visibility()
        if visibility_attr == 'public':
            visibility_bool = True
        else:
            visibility_bool = False
            
        title_attr = attr.get_title()
        description_attr = attr.get_description()
        #query_id_attr = attr.get_query_id()
        #TODO url image
        image1 = Image(url='url')
        image1.save()
        
        now = datetime.datetime.now()
        mktime(now.timetuple())
        print mktime(now.timetuple())
           
        # create the documentary file
        dossierDoc1 = Documentaryfile(title=title_attr, date=now , description=description_attr, visibility=visibility_bool, list_concepts=list_concepts, concepts_with_detailed_documents_list = concepts_with_detailed_documents_list, image=image1, user=user_attr)
        dossierDoc1.save()
        nb_concept = len(concepts_with_detailed_documents_list)
        logger.info('nb_concept = ' + str(nb_concept))
        for concept_index, concept_with_detailed_documents_list in enumerate(concepts_with_detailed_documents_list) :
            cluster1 = Cluster.objects.create(title=list_concepts[concept_index]['title'], description=list_concepts[concept_index]['abstract'], weight=list_concepts[concept_index]['score'], documentaryfile=dossierDoc1, image=image1)
            for detailed_document in concept_with_detailed_documents_list:
                logger.info(detailed_document)
                logger.info('cluster_id and doc_id = ' + str(list_concepts[concept_index]['title']+' and '+detailed_document['id']))
                #Verify if the document exist already in database
                try:
                    doc1 = Document.objects.get(pk=detailed_document['id'])
                except Document.DoesNotExist:
                    doc1 = Document.objects.create(documentId=detailed_document['id'], title=detailed_document['title'],description=detailed_document['abstract'],date=datetime.datetime.fromtimestamp(int(detailed_document['date'])).isoformat(), image=image1)
                    
                clusterDocWeight1 = Clusterdocumentweight(cluster=cluster1, document=doc1, weight=detailed_document['weight'])
                clusterDocWeight1.save()
        json= '{"documentary_file_created":' + str(dossierDoc1.id) + '}'
        logger.info(json)
        return json