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

#Copyright (c) 2012, Bartłomiej Nitoń
#All rights reserved.

#Redistribution and use in source and binary forms, with or without modification, are permitted provided 
#that the following conditions are met:

#    Redistributions of source code must retain the above copyright notice, this list of conditions and 
#    the following disclaimer.
#    Redistributions in binary form must reproduce the above copyright notice, this list of conditions 
#    and the following disclaimer in the documentation and/or other materials provided with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED 
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.

from django.db.models import Q, Max, Count
import operator

from dictionary.models import Frame_Char_Model
from dictionary.ajax_lemma_view import sortFrameChars, sortPositions, sortArguments

from django import template
register = template.Library()

def preparePositionDict(frame):
  positions_list = sortPositions(frame.positions.all())
  pos_dict = []
  arg_number = 0
  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})
    
  return pos_dict  

# do pomocy przy pobieraniu slownika w formacie pdf
@register.inclusion_tag('tex/lemma.tex')
def lemma_tex(lemma, loop_counter, q_frame_opinions, sort_reflex_vals, sort_aspect_vals, download_dict):#, q_realizations, q_real_types):
  frame_char_models = Frame_Char_Model.objects.order_by('-priority')
  frame_opinions = None
  frames = []
  if q_frame_opinions:
    frame_opinions = lemma.frame_opinions.filter(reduce(operator.or_, q_frame_opinions))
  for reflex_val in sort_reflex_vals:
    for aspect_val in sort_aspect_vals:
      matching_frames = lemma.frames.filter(characteristics__value=reflex_val,
                                            characteristics__type=frame_char_models[0].model_name 
                                            ).filter(characteristics__value=aspect_val,
                                                     characteristics__type=frame_char_models[1].model_name
                                                     ).order_by('text_rep')                          
      for frame in matching_frames:
        if not download_dict['frame_opinions'] or (frame_opinions and frame_opinions.filter(frame=frame).count() > 0):
            #frame_changed = False
          frames.append(frame)
          #  if q_realizations and frame.positions.filter(reduce(operator.or_, q_realizations)).count() > 0:    
          #   text_reps.append(changeArgsToRealizations(frame, real_arg_models, q_real_types))
          #   frame_changed = True
          #  if not frame_changed:
          #    text_reps.append(frame.text_rep)               
  return {'lemma': lemma,
          'loop_counter': loop_counter,
          'frames': frames}
  
@register.inclusion_tag('tex/frame.tex') 
def frame_tex(frame, lemma, fr_loop_counter):
  frame_chars = sortFrameChars(frame.characteristics.all())
  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').order_by('opinion__priority') 
  
  for example in frame_examples:
    example_dict = {'example' : example,
                    'arg_idxs': []}
    for pos_dict in pos_dict_ls:
      fl_args = example.arguments.filter(position=pos_dict['position'])
      for arg in pos_dict['arguments']:
        try:
          fl_args.get(arguments=arg['argument'])
          example_dict['arg_idxs'].append(arg['idx'])
        except:
          pass
    example_dict['arg_idxs'].sort
    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,
          'frame_chars'     : frame_chars,
          '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}

