#-*- coding:utf-8 -*-

from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Q

from dictionary.models import Lemma, Position

class Command(BaseCommand):
    help = 'Count positions occurrences in SloVal.'

    def handle(self, **options):
        count_positions_occurrences()  

@transaction.commit_on_success
def count_positions_occurrences():
    positions_ls = []
    lemmas = Lemma.objects.filter(Q(status__type__sym_name=u'ready') |
                                  Q(status__type__sym_name=u'checked') |
                                  Q(status__type__sym_name=u'edit_f') |
                                  Q(status__type__sym_name=u'ready_f') |
                                  Q(status__type__sym_name=u'checked_f')|
                                  Q(status__type__sym_name=u'edit_s') |
                                  Q(status__type__sym_name=u'ready_s') |
                                  Q(status__type__sym_name=u'checked_s')).filter(old=False).order_by('entry')
    print 'Finding positions.'
    for position in Position.objects.all():
        positions_ls.append({'pos_obj': position,
                             'occurrences': 0})
    print 'Counting occurrences.'
    for lemma in lemmas.all():
        print lemma
        for frame in lemma.frames.all():
            for position in frame.positions.all():
                for pos in positions_ls:
                    if pos['pos_obj'].text_rep == position.text_rep:
                        pos['occurrences'] += 1              
    print 'Updating positions.'
    for position in positions_ls:
        Position.objects.filter(text_rep=position['pos_obj'].text_rep).update(occurrences=position['occurrences'])
        