#-*- 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.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse

from common.decorators import render
from dictionary.forms import AddLemmaForm, UserCreateForm, GetVocabularyForm
from dictionary.models import *
from dictionary.ajax_lemma_view import getFrequentPositions, order_sort_rules
from accounts.models import UserSettings


@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)
  if not request.session.has_key('sort_rules_new_frames'):
    id_rules = { 'priority': None,
                 'sort_order': 'desc'}
    entry_rules = { 'priority': 1,
                    'sort_order': 'asc'}
    owner_rules = { 'priority': None,
                    'sort_order': 'desc'}
    vocabulary_rules = { 'priority': None,
                         'sort_order': 'desc'}
    status_rules = { 'priority': None,
                     'sort_order': 'desc'}
    
    sort_rules = {'id' : id_rules,
                  'entry': entry_rules,
                  'owner': owner_rules,
                  'vocabulary': vocabulary_rules,
                  'status': status_rules}
    request.session['sort_rules'] = sort_rules
  if not request.session.has_key('filter_rules'):
    request.session['filter_rules'] = {'owner': None,
                                       'vocabulary': None,
                                       'status': None,
                                       'example_source': None,
                                       'approver'      : None,
                                       'old_frames_property': None,
                                       'argument'           : None,
                                       'position' : None,
                                       'sender': None}
  if not request.session.has_key('sorted_column'):
    request.session['sorted_column'] = ''
    
  if not request.session.has_key('sort_rules_lemma_preview'):
    id_rules = { 'priority': None,
                 'sort_order': 'desc'}
    entry_rules = { 'priority': 1,
                    'sort_order': 'asc'}
    owner_rules = { 'priority': None,
                    'sort_order': 'desc'}
    vocabulary_rules = { 'priority': None,
                         'sort_order': 'desc'}
    status_rules = { 'priority': None,
                     'sort_order': 'desc'}
    
    sort_rules = {'id' : id_rules,
                  'entry': entry_rules,
                  'owner': owner_rules,
                  'vocabulary': vocabulary_rules,
                  'status': status_rules}
    request.session['sort_rules_lemma_preview'] = sort_rules
  if not request.session.has_key('filter_rules_lemma_preview'):
    request.session['filter_rules_lemma_preview'] = {'owner': None,
                                                    'vocabulary': None,
                                                    'status': None,
                                                    'example_source': None,
                                                    'approver'      : None,
                                                    'old_frames_property': None,
                                                    'argument'           : None,
                                                    'position' : None,
                                                    'sender' : None}
  if not request.session.has_key('sorted_column_lemma_preview'):
    request.session['sorted_column_lemma_preview'] = ''
    
  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 = ''
  main_sort_order = ''
  if request.session['sorted_column']:
    main_sort_field = request.session['sorted_column']['name']
    main_sort_order = request.session['sorted_column']['order']
  else:
    main_sort_field = ordered_sort_rules[0]['name']
    main_sort_order = ordered_sort_rules[0]['rules']['sort_order']
    
  auto_search = UserSettings.objects.get(user=request.user).incremental_search
  
  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_note_text': reverse('get_note_text'),
    'ajax_lemma_notes_form_submit': reverse('lemma_notes_form_submit'),
    'ajax_lemma_status_change': reverse('lemma_status_change'),
    '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_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_frame_form_submit': reverse('frame_form_submit'),
    'ajax_pos_cat_form': reverse('pos_cat_form'),
    'ajax_pos_cat_form_submit': reverse('pos_cat_form_submit'),
    'ajax_nkjp_example_form_submit': reverse('nkjp_example_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'),
    
 # 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'),
    
 # 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_reset': reverse('similar_lemmas_reset'),
    'ajax_preview_select': reverse('preview_select'),
    
 # walidacja
    'ajax_validate_new_frames': reverse('validate_new_frames'),

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

 # pokazywanie realizacji
    'ajax_show_realizations': reverse('show_realizations'),
    
 # 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
  }
  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}


@permission_required('dictionary.manage_vocabulary')
@render('manage_vocabularies.html')
def manage_vocabulary(request):
  to_return = {}
  add_lemma_form = AddLemmaForm();
  to_return['download_form'] = GetVocabularyForm()
  to_return['vocabularies'] = Vocabulary.objects.all()
  to_return['add_lemma_form'] = add_lemma_form
  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_lemma_lookup': reverse('lemma_lookup'),
    'ajax_lemma_add_form_submit': reverse('lemma_add_form_submit'),
    'ajax_get_vocabulary_stats': reverse('get_vocabulary_stats'),
    'ajax_delete_lemma': reverse('delete_lemma'),
  }
  return to_return

@permission_required('dictionary.view_notes')
@render('user_notes.html')
def user_notes(request):
  to_return = {}
  to_return['notes'] = Message.objects.filter(lemma__owner=request.user, private=False).order_by('-time')
  to_return['private_notes'] = Message.objects.filter(sender=request.user, private=True).order_by('-time')
  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'),
  }
  return to_return
  
@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.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
  
@permission_required('dictionary.create_realization')
@render('arg_realizations.html')
def manage_arg_realizations(request):
  to_return = {}
  to_return['js_vars'] = {
    'ajax_realization_arg_form': reverse('realization_arg_form'),
    'ajax_add_arg_realization': reverse('add_arg_realization'),
    'ajax_show_realizations': reverse('show_realizations'),
    'ajax_remove_realization': reverse('remove_realization'),
  }
  return to_return
