from django.conf import settings
import lxml.etree

def compute_stats_for(content, verbose=False):
    number_division = settings.DIVISIONS_FOR_STAT_ANNOTATION
    
    print "analysing content %s" % content.iri_id

    size_division = content.duration / number_division
    limits = [x * size_division for x in range(number_division+1)]
    buckets = [0] * number_division
    nb_annotations = 0
       
    for project in content.project_set.all():
        if verbose:
            print "analysing project %s " % project 
                    
        doc = lxml.etree.fromstring(project.ldt) 
            
        annotations = doc.xpath('/iri/annotations/content[@id="' + content.iri_id + '"]/ensemble/decoupage/elements/element')
        for ann in annotations:
            nb_annotations += 1  
            begin = int(ann.get('begin'))
            end = int(ann.get('dur')) + begin
                    
            #print "%s - %s" % (begin, end)
            #print ann.xpath('title')[0].text
                    
            buckets = find_buckets(buckets, limits, begin, end)
                    
            #print buckets
              
    content.stat_annotation = get_string_from_buckets(buckets)
    content.nb_annotation = nb_annotations
    content.save()
    
    if verbose:
        print "%s : %s" % (content.iri_id, buckets)
        
    return buckets

def get_string_from_buckets(buckets):
    s = "%s" % buckets
    s = s[1:-1].replace(' ', '')
    return s

def find_buckets(buckets, limits, begin, end):
    
    if len(buckets)+1 != len(limits):
        raise ValueError("There should be as many buckets as those defined by limits.")
    
    has_started = False  
        
    for i in range(len(limits)-1):
        if not has_started:
            if limits[i] <= begin and begin <= limits[i+1]:
                buckets[i] += 1
                has_started = True
                #print "Starts after timecode %s" % limits[i]
        elif limits[i] > end:
            #print "Ends before timecode %s" % limits[i]
            break
        else:
            buckets[i] += 1
            
    return buckets

def add_annotation_to_stat(content, begin, end):
    stats = content.stat_annotation
    
    if not content.nb_annotation:
        content.nb_annotation = 1
    else:
        content.nb_annotation += 1
    
    if stats:
        
        number_division = settings.DIVISIONS_FOR_STAT_ANNOTATION
        size_division = content.duration / number_division
        
        limits = [x * size_division for x in range(number_division+1)]
        buckets = [int(x) for x in stats.split(',')]
        
        buckets = find_buckets(buckets, limits, begin, end)
        content.stat_annotation = get_string_from_buckets(buckets)
    
    content.save()    

    

    