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

import operator
import string

from django import template
from django.db.models import Max, Count

from dictionary.ajax_lemma_view import sortPositions

register = template.Library()

def preparePositionDict(frame):
  alphabet = string.lowercase
  arg_number = 0
  pos_dict = []
  position_idx = 0
  positions_list = sortPositions(frame.positions.all())
  for position in positions_list:
    pos_cats_str_tab = []
    for category in position['position'].categories.order_by('priority'):
      pos_cats_str_tab.append(category.category)
    pos_cats_str = ', '.join(pos_cats_str_tab) #list(position['position'].categories.order_by('priority').all()).join(', ')
    arg_dict_list = []
    for argument in position['arguments']:
      arg_number = arg_number + 1
      arg_dict_list.append({'argument': argument,
                            'idx'     : arg_number})
    pos_dict.append({'position'     : position['position'],
                     'arguments'    : arg_dict_list,
                     'pos_cats_str' : pos_cats_str,
                     'idx'          : alphabet[position_idx].upper()})
    position_idx += 1
    
  return pos_dict  

def convtotex(example):
    example.sentence = (example.sentence.
                        replace('\\', '\\textbackslash').
                        replace('{', '\\{').
                        replace('}', '\\}').
                        replace('\\textbackslash', '\\textbackslash{}').
                        replace('#', '\\#{}').
                        replace('$', '\\${}').
                        replace('&', '\\&{}').
                        replace('%', '\\%{}').
                        replace(u'˝', '\"').
                        replace(u'­', u'\-').
                        replace(u'−', u'--').
                        replace('^', '\\^{}'))                  
    example.comment = (example.comment.
                       replace('\\', '\\textbackslash').
                       replace('{', '\\{').
                       replace('}', '\\}').
                       replace('\\textbackslash', '\\textbackslash{}').
                       replace('#', '\\#{}').
                       replace('$', '\\${}').
                       replace('&', '\\&{}').
                       replace('%', '\\%{}').
                       replace(u'˝', '\"').
                       replace(u'­', u'\-').
                       replace(u'−', u'--').
                       replace('^', '\\^{}'))

# do pomocy przy pobieraniu slownika w formacie pdf
@register.inclusion_tag('tex/lemma.tex')
def lemma_tex(lemma, loop_counter, q_frame_opinions, download_dict):
  lemma_examples = lemma.lemma_nkjp_examples.order_by('source__priority', 
                                                      'opinion__priority', 
                                                      'sentence').all()
  for example in lemma_examples:
    convtotex(example)
  frame_opinions = None
  frames = []
  if q_frame_opinions:
    frame_opinions = lemma.frame_opinions.filter(reduce(operator.or_, q_frame_opinions))
  for reflex_val in lemma.get_existing_frame_char_values(u'ZWROTNOŚĆ'):
    for neg_val in lemma.get_existing_frame_char_values(u'NEGATYWNOŚĆ'):
        for pred_val in lemma.get_existing_frame_char_values(u'PREDYKATYWNOŚĆ'):
            for aspect_val in lemma.get_existing_frame_char_values(u'ASPEKT'):
              matching_frames = lemma.get_frames_by_char_values(reflex_val=reflex_val, 
                                                                neg_val=neg_val, 
                                                                pred_val=pred_val, 
                                                                aspect_val=aspect_val).order_by('text_rep')                          
              for frame in matching_frames:
                if not lemma.phraseology_ready() and frame.phraseologic:
                    continue
                if not download_dict['frame_opinions'] or (frame_opinions and frame_opinions.filter(frame=frame).count() > 0):
                  frames.append(frame)             
  return {'lemma': lemma,
          'loop_counter': loop_counter,
          'frames': frames,
          'lemma_examples': lemma_examples}
  
@register.inclusion_tag('tex/frame.tex') 
def frame_tex(frame, lemma, fr_loop_counter):
  pos_dict_ls = preparePositionDict(frame)
  colsAlignmentTex = 'l'
  for position in frame.positions.all():
    colsAlignmentTex = colsAlignmentTex + 'l'
  
  max_args = frame.positions.annotate(num_args=Count('arguments')).aggregate(Max('num_args'))['num_args__max']
  if not max_args:
    max_args = 0 
  
  example_dict_ls = []
  frame_examples = lemma.nkjp_examples.filter(frame=frame).order_by('source__priority', 
                                                                    'opinion__priority', 
                                                                    'sentence') 
  for example in frame_examples:
    convtotex(example)
    example_dict = {'example' : example,
                    'positions': []}
    
    for pos_dict in pos_dict_ls:
      position = {'idx': pos_dict['idx'],
                  'arg_idxs': []}
      
      fl_args = example.arguments.filter(position=pos_dict['position'])
      for arg in pos_dict['arguments']:
        try:
          fl_args.get(arguments=arg['argument'])
          position['arg_idxs'].append(arg['idx'])
        except:
          pass
      position['arg_idxs'].sort
      if position['arg_idxs']:
          example_dict['positions'].append(position)
    example_dict['positions'].sort(key=operator.itemgetter('idx'))
    example_dict_ls.append(example_dict)  
  try:  
    frame_opinion = lemma.frame_opinions.filter(frame=frame).all()[0].value
  except IndexError:
    frame_opinion = ''
    
  return {'frame'           : frame,
          'lemma'           : lemma,
          'reflex'          : frame.characteristics.get(type=u'ZWROTNOŚĆ').value.value,
          'negativity'      : frame.characteristics.get(type=u'NEGATYWNOŚĆ').value.value,
          'predicativity'   : frame.characteristics.get(type=u'PREDYKATYWNOŚĆ').value.value,
          'aspect'          : frame.characteristics.get(type=u'ASPEKT').value.value,
          'fr_loop_counter' : fr_loop_counter,
          'pos_dict_ls'     : pos_dict_ls,
          'colsAlignmentTex': colsAlignmentTex,
          'max_args'        : range(max_args),
          'example_dict_ls' : example_dict_ls,
          'frame_opinion'   : frame_opinion}

