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

import datetime
import os

from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponse

import settings
from accounts.models import UserSettings
from common.decorators import render
from dictionary.ajax_jqgrid import default_sort_rules
from dictionary.filtering import all_filter_rules_loaded, default_filter_rules
from dictionary.forms import UserCreateForm, GetVocabularyForm, ArgStatsForm
from dictionary.models import PositionCategory, NKJP_Opinion, NKJP_Source, \
                              Vocabulary, Message, RealizationType
from dictionary.ajax_lemma_view import getFrequentPositions, order_sort_rules


#@permission_required('dictionary.view_lemma')
@render()
def lemma_view(request):      
  if not request.session.has_key('lemma_from_note_entry'):
    request.session['lemma_from_note_entry'] = ''
  if not request.session.has_key('lemma_from_note_id'):
    request.session['lemma_from_note_id'] = ''
  if not request.session.has_key('frequent_positions'):    
    request.session['frequent_positions'] = getFrequentPositions(10)

  # sorting rules
  if not request.session.has_key('sort_rules'):
    request.session['sort_rules'] = default_sort_rules()
  else:
      if not 'id' in request.session['sort_rules']:
          request.session['sort_rules']['id'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'entry' in request.session['sort_rules']:
          request.session['sort_rules']['entry'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'owner' in request.session['sort_rules']:
          request.session['sort_rules']['owner'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'phraseologist' in request.session['sort_rules']:
          request.session['sort_rules']['phraseologist'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'semanticist' in request.session['sort_rules']:
          request.session['sort_rules']['semanticist'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'vocabulary' in request.session['sort_rules']:
          request.session['sort_rules']['vocabulary'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'status' in request.session['sort_rules']:
          request.session['sort_rules']['status'] = { 'priority': None, 'sort_order': 'desc'}
          
  if not request.session.has_key('sort_rules_lemma_preview'):
    request.session['sort_rules_lemma_preview'] = default_sort_rules()
  else:
      if not 'id' in request.session['sort_rules_lemma_preview']:
          request.session['sort_rules_lemma_preview']['id'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'entry' in request.session['sort_rules_lemma_preview']:
          request.session['sort_rules_lemma_preview']['entry'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'owner' in request.session['sort_rules_lemma_preview']:
          request.session['sort_rules_lemma_preview']['owner'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'phraseologist' in request.session['sort_rules_lemma_preview']:
          request.session['sort_rules_lemma_preview']['phraseologist'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'semanticist' in request.session['sort_rules_lemma_preview']:
          request.session['sort_rules_lemma_preview']['semanticist'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'vocabulary' in request.session['sort_rules_lemma_preview']:
          request.session['sort_rules_lemma_preview']['vocabulary'] = { 'priority': None, 'sort_order': 'desc'}
      if not 'status' in request.session['sort_rules_lemma_preview']:
          request.session['sort_rules_lemma_preview']['status'] = { 'priority': None, 'sort_order': 'desc'}
    
  if (not request.session.has_key('filter_rules') or 
      not all_filter_rules_loaded(request.session['filter_rules'])):
    request.session['filter_rules'] = default_filter_rules()

  if (not request.session.has_key('filter_rules_lemma_preview') or
      not all_filter_rules_loaded(request.session['filter_rules_lemma_preview'])):
    request.session['filter_rules_lemma_preview'] = default_filter_rules()
    
  if not request.session.has_key('lemma_preview'):
    request.session['lemma_preview'] = False
    
  if not request.session.has_key('similar_lemmas'):
    request.session['similar_lemmas'] = ''

  ordered_sort_rules = order_sort_rules(request.session['sort_rules'])
  pos_cat_vals_objs = PositionCategory.objects.order_by('priority')
  pos_cat_vals_tab = []
  for pos_cat_val_obj in pos_cat_vals_objs:
    pos_cat_vals_tab.append(pos_cat_val_obj.category)
  
  nkjp_opinion_vals_tab = []
  nkjp_opinion_objs = NKJP_Opinion.objects.order_by('priority')
  for opinion in nkjp_opinion_objs:
    nkjp_opinion_vals_tab.append(opinion.opinion)
    
  nkjp_source_vals_tab = []
  nkjp_source_objs = NKJP_Source.objects.order_by('priority')
  for source in nkjp_source_objs:
    nkjp_source_vals_tab.append(source.source)
  
  main_sort_field = ordered_sort_rules[0]['name']
  main_sort_order = ordered_sort_rules[0]['rules']['sort_order']

  if request.user.is_authenticated():
      auto_search = UserSettings.objects.get(user=request.user).incremental_search
  else:
      auto_search = False
  
  js_vars = {
    'ajax_get_page': reverse('get_lemmas'),
    'ajax_old_frames': reverse('get_old_frames'),
    'ajax_new_frames': reverse('get_new_frames'),
    'ajax_change_ctrl': reverse('get_change_ctrl'),
    'ajax_lemma_examples': reverse('get_lemma_examples'),
    'ajax_lemma_status': reverse('get_lemma_status'),
    'ajax_lemma_notes': reverse('get_lemma_notes'),
    'ajax_lemma_preview': reverse('get_lemma_preview'),
    'ajax_get_frame_filter_options': reverse('get_frame_filter_options'),
    'ajax_get_lemma_desc': reverse('get_lemma_desc'),
    'ajax_get_actual_lemma_id': reverse('get_actual_lemma_id'),
    'ajax_user_is_authenticated': reverse('user_is_authenticated'),
    
    'ajax_semantics': reverse('semantics.views.ajax_semantics'),
    
    'ajax_get_note_text': reverse('get_note_text'),
    'ajax_lemma_notes_form_submit': reverse('lemma_notes_form_submit'),
    'ajax_status_need_validation': reverse('status_need_validation'),
    'ajax_lemma_status_change': reverse('lemma_status_change'),
    'ajax_send_miss_frames_msg': reverse('send_miss_frames_msg'),
    'ajax_position_form': reverse('position_form'),
    
    'ajax_position_lookup': reverse('position_lookup'),
    'ajax_argument_lookup': reverse('argument_lookup'),
    'ajax_argument_form': reverse('argument_form'),
    'ajax_argument_form_submit': reverse('argument_form_submit'),
    'ajax_add_position': reverse('add_position'),
    'ajax_create_position_form': reverse('create_position_form'),
    'ajax_create_position_form_submit': reverse('create_position_form_submit'),
    'ajax_save_new_frames': reverse('save_new_frames'),
    'ajax_get_ctrl_preview': reverse('get_ctrl_preview'),
    'ajax_restore_lemma': reverse('restore_lemma'),
    'ajax_frame_form': reverse('frame_form'),
    'ajax_aspect_rel_missing_frames': reverse('aspect_rel_missing_frames'),
    'ajax_add_new_frames': reverse('add_new_frames'),
    'ajax_show_skladnica_examples': reverse('show_skladnica_examples'),
    'ajax_show_frame_realizations': reverse('show_frame_realizations'),
    'ajax_frame_form_submit': reverse('frame_form_submit'),
    'ajax_pos_cat_form': reverse('pos_cat_form'),
    'ajax_can_add_position_category': reverse('can_add_position_category'),
    'ajax_pos_cat_form_submit': reverse('pos_cat_form_submit'),
    'ajax_skladnica_example_propositions': reverse('skladnica_example_propositions'),
    'ajax_xcp_example_propositions': reverse('xcp_example_propositions'),
    'ajax_nkjp_example_form_submit': reverse('nkjp_example_form_submit'),
    'ajax_semantic_example_form_submit': reverse('semantic_example_form_submit'),
    'ajax_remove_example_from_lemma': reverse('remove_example_from_lemma'),
    'ajax_get_skladnica_example': reverse('get_skladnica_example'),
    'ajax_get_xcp_example': reverse('get_xcp_example'),
    'ajax_get_frame_chars': reverse('get_frame_chars'),
    'ajax_example_opinion_form': reverse('example_opinion_form'),
    'ajax_example_opinion_form_submit': reverse('example_opinion_form_submit'),
    'ajax_can_confirm_example': reverse('can_confirm_example'),
    'ajax_confirm_nkjp_example': reverse('confirm_nkjp_example'), 
    'ajax_location': reverse('get_location'),
    'ajax_note_session_get': reverse('note_session_get'),
    'ajax_note_session_clear'  : reverse('note_session_clear'),
    'ajax_remove_lemma_note'  : reverse('remove_lemma_note'),
    'ajax_lemma_note_form'  : reverse('lemma_note_form'),
    'ajax_get_lemma_note'  : reverse('get_lemma_note'),
    'ajax_lemma_notes_modify'  : reverse('lemma_notes_modify'),
    'ajax_frame_conversion_form'  : reverse('frame_conversion_form'),
    'ajax_frame_conversion_form_submit'  : reverse('frame_conversion_form_submit'),
    'ajax_need_conversion'  : reverse('need_conversion'),
    'ajax_get_compatible_schema_chars'  : reverse('get_compatible_schema_chars'),
    
    'ajax_deselect_preview_tab': reverse('deselect_preview_tab'),
    'ajax_get_schemata': reverse('get_schemata'),
    'ajax_get_examples': reverse('get_examples'),
    'ajax_get_schemata_and_examples': reverse('get_schemata_and_examples'),
    
 # powiazywanie hasel (nieczasownikowe)
    'ajax_relate_entries'  : reverse('relate_entries'),
    'ajax_disrelate_entries'  : reverse('disrelate_entries'),
    'ajax_are_new_preview_entries_related'  : reverse('are_new_preview_entries_related'),
    
 # filtry, sortowania, ukrywanie elementow tabeli
    'ajax_sort_form'  : reverse('sort_form'),
    'ajax_filter_form'  : reverse('filter_form'),
    'ajax_sort_form_submit'  : reverse('sort_form_submit'),
    'ajax_filter_form_submit'  : reverse('filter_form_submit'),
    'ajax_sort_column'  : reverse('sort_column'),
    'ajax_save_columns': reverse('save_columns'),
    'ajax_save_columns': reverse('save_columns'),
    'ajax_get_sort_order': reverse('get_sort_order'),
    'ajax_sem_arg_form': reverse('sem_arg_form'),
    'ajax_general_preference_form': reverse('general_preference_form'),
    'ajax_synset_preference_form': reverse('synset_preference_form'),
    'ajax_relational_preference_form': reverse('relational_preference_form'),
    'ajax_synset_context_lookup': reverse('synset_context_lookup'),
    
 # czasowniki podobne
    'ajax_similar_lemmas_old_form_submit': reverse('similar_lemmas_old_form_submit'),
    'ajax_similar_lemmas_new_form_submit': reverse('similar_lemmas_new_form_submit'),
    'ajax_similar_lemmas_show_synonyms': reverse('similar_lemmas_show_synonyms'),
    'ajax_related_lemmas_show': reverse('related_lemmas_show'),
    'ajax_similar_lemmas_reset': reverse('similar_lemmas_reset'),
    'ajax_preview_select': reverse('preview_select'),
    
 # walidacja
    'ajax_validate_new_frames': reverse('validate_new_frames'),
    'ajax_validate_semantics': reverse('validate_semantics'),

 # modyfikacja przykladow nkjp
    'ajax_get_nkjp_dict_ids': reverse('get_nkjp_dict_ids'),

 # pokazywanie realizacji
    'ajax_show_realizations': reverse('show_realizations'),
    
 # uprawnienia
    'ajax_user_has_perm': reverse('user_has_perm'),

 # frazeologia
    #'ajax_has_lexicalized_args': reverse('has_lexicalized_args'),
    'ajax_phraseologic_propositions_exists': reverse('phraseologic_propositions_exists'),
    'ajax_arg_can_be_lexicalized': reverse('arg_can_be_lexicalized'),
    'ajax_assign_phraseologic_frame_form': reverse('assign_phraseologic_frame_form'),
    'ajax_assign_phraseologic_frame': reverse('assign_phraseologic_frame'),
    'ajax_entry_lookup': reverse('entry_lookup'),
    
 # inne
    'ajax_get_arg_id': reverse('get_arg_id'),
    
 # zmienne
    'ax_main_field': main_sort_field,
    'ax_sort_order': main_sort_order,
    'ax_pos_cat_vals': pos_cat_vals_tab,
    'ax_nkjp_opinion_vals': nkjp_opinion_vals_tab,
    'ax_nkjp_source_vals': nkjp_source_vals_tab,
    'ax_auto_search': auto_search,
    
    'ax_initialColNames': get_grid_col_names(request.user),
    'ax_initialColModel': get_grid_col_models(request.user)
  }
  show_cols_variables = ('colModel', 'colNames', 'remap')
  for var in show_cols_variables:
    if var in request.session:
      js_vars[var] = request.session[var] 
  
  return {'js_vars': js_vars}
  
def get_grid_col_names(user):
    if user.is_authenticated():
        names = ['Id', 'Hasło', 'Właściciel', 'Frazeolog', 'Semantyk', 'Słownik', 'Status']
    else:
        names = ['Hasło', 'Status']
    return names

def get_grid_col_models(user):
    if user.is_authenticated():
        col_models = [{ 
                        'name': 'id', 
                        'index': 'id',
                        'search': False, 
                        'hidden': True, 
                        'sortable': True
                      },
                      {
                        'name': 'entry', 
                        'index': 'entry',
                        'search': False, 
                        'hidden': False,
                        'sortable': True
                      },
                      {
                        'name': 'owner',
                        'index': 'owner',
                        'search': False, 
                        'hidden': not user.groups.filter(Q(name=u'Leksykograf') | 
                                                         Q(name=u'Superleksykograf')).exists(),
                        'sortable': True
                      },
                      {
                        'name': 'phraseologist',
                        'index': 'phraseologist',
                        'search': False, 
                        'hidden': not user.groups.filter(Q(name=u'Frazeolog') | 
                                                         Q(name=u'Superfrazeolog')).exists(),
                        'sortable': True
                      },
                      {
                        'name': 'semanticist',
                        'index': 'semanticist',
                        'search': False, 
                        'hidden': not user.groups.filter(Q(name=u'Semantyk') | 
                                                         Q(name=u'Supersemantyk')).exists(),
                        'sortable': True
                      },
                      {
                        'name': 'vocabulary',
                        'index': 'vocabulary',
                        'search': False, 
                        'hidden': False,
                        'sortable': True
                      },
                      {
                        'name': 'status',
                        'index': 'status',
                        'search': False, 
                        'hidden': False,
                        'sortable': True
                      }
                    ]
    else:
        col_models = [
                      {
                        'name': 'entry', 
                        'index': 'entry',
                        'search': False, 
                        'hidden': False,
                        'sortable': True
                      },
                      {
                        'name': 'status',
                        'index': 'status',
                        'search': False, 
                        'hidden': False,
                        'sortable': True
                      }
                    ]
    return col_models

@render('manage_vocabularies.html')
def manage_vocabulary(request):
  to_return = {}
  to_return['download_form'] = GetVocabularyForm()
  to_return['vocabularies'] = Vocabulary.objects.all()
  to_return['js_vars'] = {
    'ajax_create_vocabulary': reverse('create_vocabulary'),
    'ajax_vocab_perm_manage_form': reverse('vocab_perm_manage_form'),
    'ajax_vocab_perm_manage_form_submit': reverse('vocab_perm_manage_form_submit'),
    'ajax_get_vocabulary_stats': reverse('get_vocabulary_stats'),
    'ajax_get_other_stats': reverse('get_other_stats')
  }
  return to_return

@permission_required('dictionary.view_notes')
@render('user_notes.html')
def user_notes(request):
  to_return = {}
  notes_per_page = request.user.user_settings.notes_per_page
  all_public_notes = Message.objects.filter(recipient=request.user, 
                                            private=False).order_by('-new', '-time')
                                        
  to_return['public_notes_pages_count'] = count_pages(all_public_notes, notes_per_page)
  all_private_notes = Message.objects.filter(sender=request.user, 
                                             private=True).order_by('-time')
  to_return['private_notes_pages_count'] = count_pages(all_private_notes, notes_per_page)
  to_return['js_vars'] = {
   'ajax_get_note_text': reverse('get_note_text'),
   'ajax_remove_note': reverse('remove_note'),
   'ajax_get_lemma_from_note': reverse('get_lemma_from_note'),
   'ajax_note_session_clear': reverse('note_session_clear'),
   'ajax_notes_page': reverse('notes_page'),
  }
  return to_return
  
def count_pages(notes, notes_per_page):
    notes_count = notes.count()
    pages_count = notes_count/notes_per_page
    if notes_count%notes_per_page > 0:
        pages_count += 1
    return pages_count
  
@permission_required('dictionary.see_stats')
@render('user_statistics.html')
def user_statistics(request):
  to_return = {}
  to_return['js_vars'] = {
    'ajax_get_user_stats': reverse('get_user_stats'),
  }
  return to_return
  
@permission_required('dictionary.see_all_stats')
@render('all_statistics.html')
def all_statistics(request):
  to_return = {}
  to_return['users'] = User.objects.filter(Q(groups__permissions__codename='add_phraseologic_frames')
                                           | Q(groups__permissions__codename='add_syntactic_frames')
                                           | Q(groups__permissions__codename='add_semantic_frames')).distinct().order_by('username')  
  to_return['js_vars'] = {
    'ajax_get_user_stats': reverse('get_user_stats'),                    
  }
  return to_return

@permission_required('auth.add_user')
@render('manage_users.html')
def manage_users(request):
  to_return = {}
  create_user_form = UserCreateForm()
  to_return['new_account_form'] = create_user_form
  to_return['js_vars'] = {
    'ajax_new_account_form_submit': reverse('new_account_form_submit'), 
    'ajax_change_user_fun_form': reverse('change_user_fun_form'),         
    'ajax_change_user_fun_form_submit': reverse('change_user_fun_form_submit'),    
    'ajax_delete_user': reverse('delete_user'),
  }
  return to_return
  
@render('arg_realizations.html')
def manage_arg_realizations(request):
  to_return = {}
  to_return['realization_types'] = RealizationType.objects.order_by('priority')
  to_return['js_vars'] = {
    'ajax_realization_arg_form': reverse('realization_arg_form'),
    'ajax_add_arg_realization': reverse('add_arg_realization'),
    'ajax_add_positions_extension': reverse('add_positions_extension'),
    'ajax_show_realizations': reverse('show_realizations'),
    'ajax_remove_realization': reverse('remove_realization'),
    'ajax_create_realizations': reverse('create_realizations'),
    'ajax_argument_form': reverse('argument_form'),
    'ajax_argument_form_submit': reverse('argument_form_submit'),
    'ajax_create_position_form': reverse('create_position_form'),
    'ajax_create_position_form_submit': reverse('create_position_form_submit'),
    'ajax_positions_extension_form': reverse('positions_extension_form'),
  }
  return to_return
  
def download_dict(request, format):
    generation_date = datetime.datetime.now() - datetime.timedelta(days=1)
    walenty_file_name = '%s_%s.tar.gz' % ('walenty', generation_date.strftime('%Y%m%d'))
    walenty_path = os.path.join(settings.WALENTY_PATH, walenty_file_name)
    
    while not os.path.isfile(walenty_path):
        generation_date = generation_date - datetime.timedelta(days=1)
        walenty_file_name = '%s_%s-%s.tar.gz' % ('walenty', generation_date.strftime('%Y%m%d'), format)
        walenty_path = os.path.join(settings.WALENTY_PATH, walenty_file_name)
    
    response = HttpResponse(file(walenty_path), content_type='application/x-gzip')
    response['Content-Disposition'] = 'attachment; filename=%s' % walenty_file_name
    return response
