#-*- 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.forms import *
from dictionary.models import * 

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Group


class IntegerRangeField(forms.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        forms.IntegerField.__init__(self, verbose_name, name, **kwargs)
    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)


class AddPositionForm(Form):
  frequent_positions = ChoiceField(choices=[], label=u'Najczęściej wykorzystywane pozycje', required=False)
  filtered_positions = forms.CharField(label=u'Znajdź potrzebną pozycję', required=False)

  def __init__(self, freq_pos, pos_length=30, *args, **kwargs):
    super(AddPositionForm, self).__init__(*args, **kwargs)
    self.fields['frequent_positions'].choices = freq_pos
    self.fields['filtered_positions'].widget = forms.TextInput(attrs={'size':pos_length})
    

class AddArgumentForm(Form):
  arg_model_name = ModelChoiceField(queryset=None, label=u'Typ argumentu:', required=True)
  
  def __init__(self, value = None, show_related=False, model_queryset=Argument_Model.objects.all(), *args, **kwargs):
    super(AddArgumentForm, self).__init__(*args, **kwargs)
    self.fields['arg_model_name'].initial = value
    if not show_related:
      self.fields['arg_model_name'].queryset = Argument_Model.objects.filter(realization_only=False)
    else:
      self.fields['arg_model_name'].queryset = model_queryset
    
    
class AtributeChoiceForm(Form):
  atr_value = ModelChoiceField(queryset=Atribute_Model.objects.none(), required=False)
  
  def __init__(self, values, label, value = None, show_related=False, *args, **kwargs):
    super(AtributeChoiceForm, self).__init__(*args, **kwargs)
    if not show_related:
      self.fields['atr_value'].queryset = values.filter(realization_only=False)
    else:
      self.fields['atr_value'].queryset = values
    self.fields['atr_value'].label = label
    self.fields['atr_value'].initial = value
   
    
class AtributeTextForm(Form):
  atr_value = forms.CharField()

  def __init__(self, label, value = None, *args, **kwargs):
    super(AtributeTextForm, self).__init__(*args, **kwargs)
    self.fields['atr_value'].label = label
    self.fields['atr_value'].initial = value
    
    
class FrameForm(Form):
  aspect = ModelChoiceField(label=u'Aspekt', queryset=Frame_Characteristic.objects.none(), required=False)
  reflex = ModelChoiceField(label=u'Zwrotność', queryset=Frame_Characteristic.objects.none(), required=False)
  frame_opinion = ModelChoiceField(label=u'Ocena ramki', 
                                   queryset=Frame_Opinion_Value.objects.order_by('priority'), 
                                   required=False)
  
  def __init__(self, aspect_values, reflex_values, aspect_val=None, reflex_val=None,
               frame_opinion_val=None, *args, **kwargs):
    super(FrameForm, self).__init__(*args, **kwargs)
    self.fields['aspect'].queryset = aspect_values
    self.fields['aspect'].initial = aspect_val
    self.fields['reflex'].queryset = reflex_values
    self.fields['reflex'].initial = reflex_val
    self.fields['frame_opinion'].initial = frame_opinion_val
    
class Pos_Cat_Form(Form):
  category = ModelChoiceField(label=u'Kategoria pozycji', queryset=PositionCategory.objects.none(), required=False)
  control = ModelChoiceField(label=u'Kontrola', queryset=PositionCategory.objects.none(), required=False)
  
  def __init__(self, category_val=None, control_val=None, *args, **kwargs):
    super(Pos_Cat_Form, self).__init__(*args, **kwargs)
    self.fields['category'].queryset = PositionCategory.objects.filter(control=False).order_by('priority')
    self.fields['control'].queryset = PositionCategory.objects.filter(control=True).order_by('priority')
    self.fields['category'].initial = category_val
    self.fields['control'].initial = control_val

class AddNkjpExampleForm(ModelForm):
  sentence = forms.CharField(label=u'Przykładowe zdanie', widget = Textarea(attrs={'cols': 80, 'rows': 1}))
  source = ModelChoiceField(label=u'Źródło', queryset=NKJP_Source.objects.all())
  opinion = ModelChoiceField(label=u'Ocena doboru', queryset=NKJP_Opinion.objects.all())
  comment = forms.CharField(label=u'Dodatkowy komentarz', widget = Textarea(attrs={'cols': 80, 'rows': 1})) 

  class Meta:
    model = NKJP_Example
    exclude = ('frame', 'arguments', 'approvers', 'approved',)

class MessageForm(ModelForm):
  private = forms.BooleanField(label=u'Prywatna', required=False, initial=False)
  topic = forms.CharField(label=u'Temat', widget = Textarea(attrs={'cols': 80, 'rows': 1}))
  message_text = forms.CharField(label=u'Treść', widget = Textarea(attrs={'cols': 80, 'rows': 20})) 
  
  def __init__(self, hide_private=False, topic='', *args, **kwargs):
    super(MessageForm, self).__init__(*args, **kwargs)
    if hide_private:
      self.fields['private'].widget = forms.HiddenInput()
      self.fields['private'].initial = False
      self.fields['topic'].initial = topic

  class Meta:
    model = Message
    exclude = ('sender', 'lemma', 'new', 'recipient')

############################ sorting, filtering    
class FilterForm(Form):
  owner = ModelChoiceField(label=u'Właściciel', queryset=User.objects.none(), required=False)
  vocabulary = ModelChoiceField(label=u'Słownik', queryset=Vocabulary.objects.none(), required=False)
  status = ModelChoiceField(label=u'Status', queryset=Lemma_Status.objects.none(), required=False)
  has_old_frames_property = ModelChoiceField(label=u'Posiada właściwość (stare ramki)', queryset=Old_Frame_Property.objects.all(), 
                                         required=False)
  has_message_from = ModelChoiceField(label=u'Posiada wiadomość od', queryset=User.objects.all(), 
                                         required=False)
  example_source = ModelChoiceField(label=u'Posiada przykład', queryset=NKJP_Source.objects.filter(confirmation_required=True), 
                                         required=False)
  approver = ModelChoiceField(label=u'Zatwierdzający przykład', queryset=User.objects.filter(Q(groups__permissions__codename='confirm_example') 
                                                                                             | Q(is_superuser=True)).distinct(), 
                                         required=False)
  
  has_argument = forms.CharField(label=u'Posiada argument', required=False)
  has_position = forms.CharField(label=u'Posiada pozycję', required=False) 
  
  def __init__(self, users, vocabularies, statuses, sel_user=None, 
               sel_vocabulary=None, sel_status=None, sel_old_property=None,
               sel_has_argument='', sel_has_position='', can_confirm_example=False,
               sel_example_source=None, sel_approver=None, sel_sender=None, *args, **kwargs):
    super(FilterForm, self).__init__(*args, **kwargs)
    self.fields['owner'].queryset = users
    self.fields['vocabulary'].queryset = vocabularies
    self.fields['status'].queryset = statuses
    self.fields['owner'].initial = sel_user
    self.fields['vocabulary'].initial = sel_vocabulary
    self.fields['status'].initial = sel_status
    if can_confirm_example:
      self.fields['example_source'].initial = sel_example_source
      self.fields['approver'].initial = sel_approver
    else:
      self.fields['example_source'].widget = self.fields['example_source'].hidden_widget()
      self.fields['example_source'].initial = None
      self.fields['approver'].widget = self.fields['approver'].hidden_widget()
      self.fields['approver'].initial = None
    self.fields['has_old_frames_property'].initial = sel_old_property
    self.fields['has_argument'].initial = sel_has_argument
    self.fields['has_position'].initial = sel_has_position
    self.fields['has_message_from'].initial = sel_sender
    
class SortForm(Form):
  id_priority = forms.IntegerField(label=u'Identyfikator', required=False, 
                                   widget=forms.TextInput(attrs={'size':'2'}))
  id_sort_order = ChoiceField(choices=[], label=u'', required=False)
  entry_priority = forms.IntegerField(label=u'Hasło', required=False, 
                                      widget=forms.TextInput(attrs={'size':'2'}))
  entry_sort_order = ChoiceField(choices=[], label=u'', required=False)
  owner_priority = forms.IntegerField(label=u'Właściciel', required=False, 
                                      widget=forms.TextInput(attrs={'size':'2'}))
  owner_sort_order = ChoiceField(choices=[], label=u'', required=False)
  vocabulary_priority = forms.IntegerField(label=u'Słownik', required=False, 
                                           widget=forms.TextInput(attrs={'size':'2'}))
  vocabulary_sort_order = ChoiceField(choices=[], label=u'', required=False)  
  status_priority = forms.IntegerField(label=u'Status', required=False, 
                                       widget=forms.TextInput(attrs={'size':'2'}))
  status_sort_order = ChoiceField(choices=[], label=u'', required=False)
    
    
  def __init__(self,  
          id_order_choice=None, id_priority_choice=None, 
          entry_order_choice=None, entry_priority_choice=None,
          owner_order_choice=None, owner_priority_choice=None,
          vocabulary_order_choice=None, vocabulary_priority_choice=None,
          status_order_choice=None, status_priority_choice=None,
           *args, **kwargs):
    super(SortForm, self).__init__(*args, **kwargs)
          
    order_choices = [(None, u'--------')]
    order_choices.append((u'desc', u'malejąco'))
    order_choices.append((u'asc', u'rosnąco'))
    
    self.fields['id_sort_order'].choices = order_choices
    self.fields['entry_sort_order'].choices = order_choices
    self.fields['owner_sort_order'].choices = order_choices
    self.fields['vocabulary_sort_order'].choices = order_choices
    self.fields['status_sort_order'].choices = order_choices
    
    self.fields['id_sort_order'].initial = id_order_choice
    self.fields['entry_sort_order'].initial = entry_order_choice
    self.fields['owner_sort_order'].initial = owner_order_choice
    self.fields['vocabulary_sort_order'].initial = vocabulary_order_choice
    self.fields['status_sort_order'].initial = status_order_choice
    
    self.fields['id_priority'].initial = id_priority_choice
    self.fields['entry_priority'].initial = entry_priority_choice
    self.fields['owner_priority'].initial = owner_priority_choice
    self.fields['vocabulary_priority'].initial = vocabulary_priority_choice
    self.fields['status_priority'].initial = status_priority_choice

####################### CZASOWNIKI PODOBNE ##########################################3
class SimilarLemmasNewForm(Form):
  status = ModelChoiceField(label=u'Minimalny status', queryset=Lemma_Status.objects.none(), required=False)
  compatibility = IntegerRangeField(label=u'Skala podobieństwa [%]', required=True, 
                                          min_value=1, max_value=100,
                                          widget=forms.TextInput(attrs={'size':'3'})) 
  
  def __init__(self, statuses, compatibility=50, *args, **kwargs):
    super(SimilarLemmasNewForm, self).__init__(*args, **kwargs)
    self.fields['status'].queryset = statuses
    
class SimilarLemmasOldForm(Form):
  compatibility = IntegerRangeField(label=u'Skala podobieństwa [%]', required=True, 
                                    min_value=1, max_value=100,
                                    widget=forms.TextInput(attrs={'size':'3'}))
  
  def __init__(self, compatibility=50, *args, **kwargs):
    super(SimilarLemmasOldForm, self).__init__(*args, **kwargs)
    
    
##################### Słowniki ######################################
class GetVocabularyForm(Form):
  vocabulary = ModelMultipleChoiceField(label=u'Słownik', queryset = Vocabulary.objects.all())
  format = ModelChoiceField(label=u'Format wyjściowy', queryset=VocabularyFormat.objects.all())
  frame_opinion = ModelMultipleChoiceField(label=u'Rodzaje ramek', queryset = Frame_Opinion_Value.objects.all())
  lemma_status = ModelMultipleChoiceField(label=u'Statusy haseł', queryset = Lemma_Status.objects.all())
  realization = ModelMultipleChoiceField(label=u'Dodaj realizacje', 
                                         queryset = Argument_Model.objects.filter(has_realizations=True).order_by('pk'))
  owner = ModelMultipleChoiceField(label = u'Właściciele', 
                                  queryset = User.objects.filter(Q(groups__permissions__codename='change_lemmas') 
                                                                 | Q(is_superuser=True)).distinct())

class ManageVocabPermForm(ModelForm):
  managers = ModelMultipleChoiceField(label=u'Zarządcy', queryset = User.objects.all())
  editors = ModelMultipleChoiceField(label=u'Edytorzy', queryset = User.objects.all())
  viewers = ModelMultipleChoiceField(label=u'Obserwatorzy', queryset = User.objects.all())
  
  class Meta:
    model = Vocabulary
    exclude = ('name', )
  
  def __init__(self, managers, editors, viewers, *args, **kwargs):
    super(ManageVocabPermForm, self).__init__(*args, **kwargs)
    self.fields['managers'].initial = [c.pk for c in managers.all()]
    self.fields['editors'].initial = [c.pk for c in editors.all()]
    self.fields['viewers'].initial = [c.pk for c in viewers.all()]  

class AddLemmaForm(Form):
  entry = forms.CharField(label=u'Hasło', required=True)
  base_lemma = forms.CharField(label=u'Bazowa forma hasła', required=False)

  def __init__(self, lemma_length=30, *args, **kwargs):
    super(AddLemmaForm, self).__init__(*args, **kwargs)
    self.fields['base_lemma'].widget = forms.TextInput(attrs={'size':lemma_length})
    
#################### Zarzadzanie uzytkownikami ###################################
class UserCreateForm(UserCreationForm):
    group = ModelChoiceField(label=u'Funkcja', queryset=Group.objects.all(), 
                              required=True)
 
    class Meta:
        model = User
        fields = ("username", 'email', "password1", "password2")
        
class ChangeUserFunctionForm(Form):
    user = ModelChoiceField(label=u'Użytkownik', queryset=User.objects.all(), 
                              required=True)
    group = ModelChoiceField(label=u'Funkcja', queryset=Group.objects.all(), 
                              required=True)
    
    def __init__(self, user_id=-1, *args, **kwargs):
      super(ChangeUserFunctionForm, self).__init__(*args, **kwargs)
      if user_id >=0:
        user = User.objects.get(id=user_id)
        self.fields['user'].initial = user
        if not user.is_superuser:
          self.fields['group'].initial = user.groups.all()[0]
            
