from django.conf import settings #@UnresolvedImport
from ldt.ldt_utils.models import Segment, ContentStat, POL_INDICES
import datetime

def update_stat_content(content):
    
    nb_division = settings.DIVISIONS_FOR_STAT_ANNOTATION
    
    segments = Segment.objects.filter(content=content).select_related(depth=1) #@UndefinedVariable
    buckets = [0] * nb_division 
    
    size_division = content.duration / nb_division
    limits = [x * size_division for x in range(nb_division+1)]
    nb_annotation = len(segments)
    
    contentstat, created = ContentStat.objects.get_or_create(content=content)

    pol_stats = [0]*len(POL_INDICES)
    
    min_update_ts = datetime.datetime.min

    for segment in segments:
        
        begin = segment.start_ts
        end = segment.start_ts + segment.duration
        
        if segment.is_polemic('OK'):
            pol_stats[POL_INDICES['pol_positive']] += 1
        if segment.is_polemic('KO'):
            pol_stats[POL_INDICES['pol_negative']] += 1
        if segment.is_polemic('Q'):
            pol_stats[POL_INDICES['pol_question']] += 1
        if segment.is_polemic('REF'):
            pol_stats[POL_INDICES['pol_reference']] += 1
        
        buckets = find_buckets(buckets, limits, begin, end)
        if segment.project_obj.modification_date > min_update_ts:
            min_update_ts = segment.project_obj.modification_date
    
    contentstat.polemics_volume = pol_stats
    contentstat.annotation_volume = buckets
    contentstat.nb_annotations = nb_annotation
    contentstat.last_annotated = min_update_ts
    
    contentstat.save()
 
   
def update_stat_project(project, contents_only=[]):
    
    if contents_only:
        contents = contents_only
    else:
        contents = project.contents.all()
            
    for c in contents:
        update_stat_content(c)
            
    return True
    
def add_annotation_to_stat(content, begin, end):
    nb_division = settings.DIVISIONS_FOR_STAT_ANNOTATION
    
    size_division = content.duration / nb_division
    limits = [x * size_division for x in range(nb_division+1)]    
    
    buckets = find_buckets(content.annotation_volume, limits, begin, end)
    
    contentstat, created = ContentStat.objects.get_or_create(content=content) #@UnusedVariable @UndefinedVariable
    contentstat.annotation_volume = buckets
    contentstat.last_annotated = datetime.datetime.now() #@UndefinedVariable
      
    contentstat.save()        

def get_string_from_buckets(buckets):
    return ','.join([str(b) for b in buckets])

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
