from django.conf import settings
from ldt.ldt_utils.models import Segment
import datetime

def update_stat_content(content):
    
    nb_division = settings.DIVISIONS_FOR_STAT_ANNOTATION
    
    segments = Segment.objects.filter(content=content)
    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)
    
    content.pol_positive = 0
    content.pol_negative = 0
    content.pol_question = 0
    content.pol_reference = 0

    for segment in segments:
        
        begin = segment.start_ts
        end = segment.start_ts + segment.duration
        
        if segment.is_polemic('OK'):
            content.pol_positive += 1
        if segment.is_polemic('KO'):
            content.pol_negative += 1
        if segment.is_polemic('Q'):
            content.pol_question += 1
        if segment.is_polemic('REF'):
            content.pol_reference += 1
        
        buckets = find_buckets(buckets, limits, begin, end)
        
    content.annotation_volume = buckets
    content.nb_annotation = nb_annotation
    
    content.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, polemics=[]):
    nb_division = settings.DIVISIONS_FOR_STAT_ANNOTATION

    if not content.nb_annotation or not content.stat_annotation:
        content.nb_annotation = 1
        content.stat_annotation = get_empty_stat_vector()
    
    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)
    content.annotation_volume = buckets
    content.last_annotated = datetime.datetime.now()
    
    for polemic in polemics:
        update_polemic_stat(content, polemic)
    
    content.save()        

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

def get_buckets_from_string(string):
    return [int(x) for x in string.split(',')]

def get_empty_stat_vector():
    return [0] * (settings.DIVISIONS_FOR_STAT_ANNOTATION + 4) # + 4 for polemic syntax

def get_empty_stat_field():
    return ("%s" % get_empty_stat_vector())[1:-1].replace(' ', '')

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 update_polemic_stat(content, polemic_hashtag):
    if polemic_hashtag == "OK":
        content.pol_positive += 1
    if polemic_hashtag == "KO":
        content.pol_negative += 1
    if polemic_hashtag == "Q":
        content.pol_question += 1
    if polemic_hashtag == "REF":
        content.pol_reference += 1
        
    return content

