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

import datetime

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Group, User
from django.db.models import Q
from django.forms import *

from dictionary.models import *
from semantics.models import FrameOpinion
#Frame, Argument_Model, AttrValueSelectionMode, \
#                              AttrValuesSeparator, Atribute_Value, PositionCategory, \
#                              Argument, Atribute_Model, ArgRealOpinion, Frame_Characteristic, \
#                              Frame_Opinion_Value, B_Frame, Old_Frame, NKJP_Source, NKJP_Opinion, \
#                              NKJP_Example, Message, POS, Vocabulary, Old_Frame_Property, \
#                              Lemma_Status, VocabularyFormat                             

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, 
               pos_tag='verb', phraseologic_frame=False, 
               *args, **kwargs):
    super(AddPositionForm, self).__init__(*args, **kwargs)
    self.fields['frequent_positions'].choices = freq_pos
    if pos_tag == 'verb' and not phraseologic_frame:
        self.fields['filtered_positions'].widget = forms.TextInput(attrs={'size': pos_length})
    else:
        self.fields['filtered_positions'].widget = forms.HiddenInput()
        
class AssignPhraseologicFrameForm(Form):
  phraseologic_frame = ModelChoiceField(label=u'Schemat bazowy', 
                                        queryset=Frame.objects.none(), 
                                        required=True)
  entry = forms.CharField(label=u'Hasło', required=True)

  def __init__(self, phraseologic_frame, 
                *args, **kwargs):
    super(AssignPhraseologicFrameForm, self).__init__(*args, **kwargs)
    self.fields['phraseologic_frame'].initial = phraseologic_frame
    self.fields['phraseologic_frame'].widget = forms.HiddenInput()
    
###########################################################
class AddArgumentForm(Form):
  arg_type = ModelChoiceField(queryset=Argument_Model.objects.order_by('priority').all(), 
                              label=u'Typ', 
                              required=True)
  
  def __init__(self, value=None, empty_label=False,
               model_queryset=Argument_Model.objects.order_by('priority').all(),
               lemma_pos=None, label='Typ', *args, **kwargs):
    super(AddArgumentForm, self).__init__(*args, **kwargs)
    self.fields['arg_type'].label = label
    if empty_label:
        self.fields['arg_type'].empty_label = None
    if lemma_pos:
        model_queryset = model_queryset.filter(poss=lemma_pos)
    self.fields['arg_type'].queryset = model_queryset.all()
    self.fields['arg_type'].initial = value

class TextAttrMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset,
                  *args, **kwargs):
        widgets = [forms.widgets.Select(choices=[(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()]),
                   forms.widgets.Select(choices=[(sep.id, sep.symbol) for sep in value_separator_queryset.all()]),
                   forms.widgets.TextInput()]
        super(TextAttrMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1], value[2]]
        else:
            return [None, None, '']

class TextAttrMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        all_fields = [
            ChoiceField(),
            ChoiceField(),
            forms.CharField()]
        super(TextAttrMultiValueField, self).__init__(all_fields, *args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1], data_list[2]]
        return [None, None, '']
    
class TextAttrMultiValueForm(Form):
  value = TextAttrMultiValueField()
  
  def __init__(self, 
                label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.all(),
                value_separator_queryset=AttrValuesSeparator.objects.all(),
                selection_mode=None,
                value_separator=None,
                lemmas_text='',
                *args, **kwargs):
    super(TextAttrMultiValueForm, self).__init__(*args, **kwargs)
    self.fields['value'].widget = TextAttrMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                                value_separator_queryset=value_separator_queryset)
    self.fields['value'].initial = [selection_mode, value_separator, lemmas_text]
    self.fields['value'].label = label

################################################################################
class ValueAttrMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset, 
                  values_queryset,
                  *args, **kwargs):
        widgets = [forms.widgets.Select(choices=[(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()]),
                   forms.widgets.Select(choices=[(sep.id, sep.symbol) for sep in value_separator_queryset.all()]),
                   forms.widgets.SelectMultiple(choices=[(value.id, value.name) for value in values_queryset.all()])]
        super(ValueAttrMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1], value[2]]
        else:
            return [None, None, []]

class ValueAttrMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(ValueAttrMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1], data_list[2]]
        return [None, None, []]
    
class ValueAttrMultiValueForm(Form):
  value = ValueAttrMultiValueField()
  
  def __init__(self, 
                label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.none(),
                value_separator_queryset=AttrValuesSeparator.objects.none(),
                values_queryset=AttributeParameterModel.objects.none(),
                selection_mode=None, 
                value_separator=None, 
                values=[],
                *args, **kwargs):
    super(ValueAttrMultiValueForm, self).__init__(*args, **kwargs)
    self.fields['value'].widget = ValueAttrMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                            value_separator_queryset=value_separator_queryset,
                                                            values_queryset=values_queryset)
    self.fields['value'].initial = [selection_mode, value_separator, values]
    self.fields['value'].label = label

class CreatePositionForm(Form):
    category = ModelChoiceField(queryset=PositionCategory.objects.filter(control=False),
                                label=u'Funkcja', 
                                required=False)
    def __init__(self, category=None, *args, **kwargs):
        super(CreatePositionForm, self).__init__(*args, **kwargs)
        self.fields['category'].initial = category

class PositionsMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset,
                  *args, **kwargs):
        sel_mode_choices = [('', '------')]
        sel_mode_choices.extend([(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()])
        separator_choices = [(sep.id, sep.symbol) for sep in value_separator_queryset.all()]
        widgets = [forms.widgets.Select(choices=sel_mode_choices),
                   forms.widgets.Select(choices=separator_choices)]
        super(PositionsMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1]]
        else:
            return [None, None]

class PositionsMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(PositionsMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1]]
        return [None, None]

class PositionsForm(Form):
    value_positions = PositionsMultiValueField()
  
    def __init__(self,  label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.none(),
                value_separator_queryset=AttrValuesSeparator.objects.none(),
                selection_mode=None, 
                value_separator=None,
                *args, **kwargs):
        super(PositionsForm, self).__init__(*args, **kwargs)
        self.fields['value_positions'].widget = PositionsMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                                          value_separator_queryset=value_separator_queryset)
        self.fields['value_positions'].initial = [selection_mode, value_separator]
        self.fields['value_positions'].label = label


class ArgumentsMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset,
                  *args, **kwargs):
        selection_mode_widget = forms.widgets.Select(choices=[(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()])
        separator_widget = forms.widgets.Select(choices=[(sep.id, sep.symbol) for sep in value_separator_queryset.all()])
        if selection_mode_queryset.count() < 2:
            selection_mode_widget.attrs['hidden'] = True
        if value_separator_queryset.count() < 2:
            separator_widget.attrs['hidden'] = True
        widgets = [selection_mode_widget, separator_widget]
        super(ArgumentsMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1]]
        else:
            return [None, None]

class ArgumentsMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(ArgumentsMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1]]
        return [None, None]

class ArgumentsForm(Form):
    value_arguments = ArgumentsMultiValueField()
    value_realizations = ModelMultipleChoiceField(queryset=Argument.objects.none(), 
                                                  required=False, label=u'Rozwinięcia typu frazy')
  
    def __init__(self,  label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.none(),
                value_separator_queryset=AttrValuesSeparator.objects.none(),
                selection_mode=None, 
                value_separator=None,
                base_arg=None,
                sel_realizations=[],
                form_type='standard',
                *args, **kwargs):
        super(ArgumentsForm, self).__init__(*args, **kwargs)
        self.fields['value_arguments'].widget = ArgumentsMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                                          value_separator_queryset=value_separator_queryset)
        self.fields['value_arguments'].initial = [selection_mode, value_separator]
        self.fields['value_arguments'].label = label
        phrase_type_extensions = ArgRealization.objects.none()
        if base_arg:
            phrase_type_extensions = base_arg.realizations.filter(type__sym_name='phrase_type')
        if phrase_type_extensions.exists():
            realizations_ids = []
            for realization in phrase_type_extensions.all():
                argument = realization.argument
                argument_model = Argument_Model.objects.get(arg_model_name=argument.type)
                if argument_model.active:
                    realizations_ids.append(argument.id)
            self.fields['value_realizations'].queryset = Argument.objects.filter(id__in=realizations_ids).order_by('text_rep')
            self.fields['value_realizations'].initial = sel_realizations
        else:
            self.fields.pop('value_realizations')
        if 'value_realizations' in self.fields and form_type == 'realization_main_arg':
            self.fields.pop('value_realizations')


class SelectArgumentForm(Form):
  argument = ModelChoiceField(queryset=Argument.objects.none(), 
                              required=True) 
  
  def __init__(self,  label='',
                *args, **kwargs):
    super(SelectArgumentForm, self).__init__(*args, **kwargs)
    self.fields['argument'].label = label    


class ArgumentAttrChoiceForm(Form):
  value = ModelChoiceField(queryset=Atribute_Model.objects.none(), required=False)
  
  def __init__(self, values, label, value=None,
               lemma_pos=None, *args, **kwargs):
    super(ArgumentAttrChoiceForm, self).__init__(*args, **kwargs)
    self.fields['value'].initial = value
    self.fields['value'].label = label
    self.fields['value'].queryset = values
######################################################################    
class ArgPropositionsForm(Form):
  freq_coordinated = forms.TypedChoiceField(choices=[('', '------')], 
                                            label=u'Często koordynujące się typy fraz:', 
                                            required=False)
  
  def __init__(self, freq_coor_choices=None,
               sel_argument=None, 
               *args, **kwargs):
    super(ArgPropositionsForm, self).__init__(*args, **kwargs)
    if freq_coor_choices:
        choices = [('', '---------')]
        self.fields['freq_coordinated'].choices = choices + freq_coor_choices
        if sel_argument:
            self.fields['freq_coordinated'].initial = sel_argument

class ArgRealOpinionForm(Form):
  opinion = ModelChoiceField(queryset=ArgRealOpinion.objects.order_by('priority'), 
                             label=u'Opinia', required=True)
  
  def __init__(self, sel_opinion=None, *args, **kwargs):
    super(ArgRealOpinionForm, self).__init__(*args, **kwargs)
    self.fields['opinion'].initial = sel_opinion

class AttributeChoiceMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(AttributeChoiceMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1]]
        return [None, []]
    
class AttributeChoiceMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  parameter_type_queryset, subparameters_queryset,
                  *args, **kwargs):
        widgets = []
        parameter_model_choices = [('', '---------')]
        parameter_model_choices.extend([(param_type.id, param_type.name) for param_type in parameter_type_queryset.all()])
        parameter_type_widget = forms.widgets.Select(choices=parameter_model_choices)
        widgets.append(parameter_type_widget)
        if subparameters_queryset.exists():
            subparameters_widget = forms.widgets.SelectMultiple(choices=[(subparam.id, subparam.name) for subparam in subparameters_queryset.all()])
            widgets.append(subparameters_widget)
        super(AttributeChoiceMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1]]
        else:
            return [None, []]
    
class AtributeChoiceForm(Form):
  value_parameter = AttributeChoiceMultiValueField()
  
  def __init__(self, values, label='', value=None, 
                subparameters=AttributeSubparameter.objects.none(),
                sel_subparameters=[],#show_related=False, 
                lemma_pos=None, *args, **kwargs):
    super(AtributeChoiceForm, self).__init__(*args, **kwargs)
    # czy pokazywac wartosci mogace wystepowac jedynie jako w realizacjach argumentow () 
    # @TODO zmienic nazwe flagi show_related bo mylaca
    values = values.exclude(related=True)
    if lemma_pos:
        values = values.filter(poss=lemma_pos)
    self.fields['value_parameter'].widget = AttributeChoiceMultiValueWidget(parameter_type_queryset=values,
                                                                            subparameters_queryset=subparameters)
    self.fields['value_parameter'].initial = [value, sel_subparameters]
    self.fields['value_parameter'].label = label
    
class AtributeTextForm(Form):
  value = forms.CharField()

  def __init__(self, label, value = None,
                *args, **kwargs):
    super(AtributeTextForm, self).__init__(*args, **kwargs)
    self.fields['value'].label = label
    self.fields['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)
  negativity = ModelChoiceField(label=u'*Negatywność', queryset=Frame_Characteristic.objects.none(), 
                                required=False)
  predicativity = ModelChoiceField(label=u'*Predykatywność', queryset=Frame_Characteristic.objects.none(), 
                                   required=False)
  frame_opinion = ModelChoiceField(label=u'*Ocena schematu', 
                                   queryset=Frame_Opinion_Value.objects.order_by('priority'), 
                                   required=False)
  base_frame = ModelChoiceField(label=u'Schemat bazowy', 
                                queryset=Frame.objects.filter(base=True), 
                                required=False)
  propose_B = ModelChoiceField(label=u'Proponowane schematy [inne]', queryset=B_Frame.objects.none(), 
                               required=False)
  propose_skladnica = ModelChoiceField(label=u'Proponowane schematy [Składnica]', queryset=Old_Frame.objects.none(), 
                             required=False)
  propose_phraseology = ModelChoiceField(label=u'*Proponowane schematy [frazeologia]', queryset=Frame.objects.none(), 
                                         required=False)
  
  def __init__(self, aspect_values, reflex_values, neg_values, pred_values, 
               proposed_frames_skladnica, proposed_frames_B,
               proposed_phraseology_frames, pos,
               aspect_val=None, reflex_val=None, neg_val=None, pred_val=None,
               frame_opinion_val=None, edit=False, phraseologic_modification=False,
               *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['negativity'].queryset = neg_values
    self.fields['negativity'].initial = neg_val
    self.fields['predicativity'].queryset = pred_values
    self.fields['predicativity'].initial = pred_val
    self.fields['frame_opinion'].initial = frame_opinion_val
    if proposed_frames_skladnica:
        self.fields['propose_skladnica'].queryset = proposed_frames_skladnica.order_by('old_frame_value')
    else:
        self.fields['propose_skladnica'].widget = forms.HiddenInput()
    if proposed_frames_B and proposed_frames_B.count() > 0:
        self.fields['propose_B'].queryset = proposed_frames_B.order_by('text_id')
    else:
        self.fields['propose_B'].widget = forms.HiddenInput()
    if edit or pos.tag != 'verb' or phraseologic_modification:
        self.fields['base_frame'].widget = forms.HiddenInput()
    
    self.fields['propose_phraseology'].queryset = proposed_phraseology_frames
    if not phraseologic_modification or not proposed_phraseology_frames.exists():
        self.fields['propose_phraseology'].widget = forms.HiddenInput()
        self.fields['propose_phraseology'].widget.attrs['disabled'] = 'disabled'
        
class FrameConversionForm(Form):
  frame_versions = ModelChoiceField(label=u'Wersja schematu',
                                    queryset=Frame.objects.none(), 
                                    required=True)
  
  def __init__(self, frame_versions, *args, **kwargs):
    super(FrameConversionForm, self).__init__(*args, **kwargs)
    self.fields['frame_versions'].queryset = frame_versions
        
class FrameAspectForm(Form):
  aspect = ModelChoiceField(label='', queryset=Frame_Characteristic.objects.filter(type=u'ASPEKT'), 
                            required=True)
  
  def __init__(self, aspect_val=Frame_Characteristic.objects.filter(type=u'ASPEKT', value__value='_'), 
               *args, **kwargs):
    super(FrameAspectForm, self).__init__(*args, **kwargs)
    self.fields['aspect'].initial = aspect_val

class FrameOpinionForm(Form):
    opinion = ModelChoiceField(label='', queryset=Frame_Opinion_Value.objects.order_by('priority'), 
                               required=True)
  
    def __init__(self, opinion_val=Frame_Opinion_Value.objects.order_by('priority')[0], 
                 *args, **kwargs):
        super(FrameOpinionForm, self).__init__(*args, **kwargs)
        self.fields['opinion'].initial = opinion_val 
          
    
class Pos_Cat_Form(Form):
  category = ModelChoiceField(label=u'Funkcja', queryset=PositionCategory.objects.none(), required=False)
  control = ModelMultipleChoiceField(label=u'Kontrola', queryset=PositionCategory.objects.none(), required=False)
  
  def __init__(self, part_of_speech, category_val=None, control_val=None, *args, **kwargs):
    super(Pos_Cat_Form, self).__init__(*args, **kwargs)
    self.fields['category'].queryset = PositionCategory.objects.filter(poss=part_of_speech,
                                                                       control=False).order_by('priority')
    self.fields['control'].queryset = PositionCategory.objects.filter(poss=part_of_speech,
                                                                      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', 'semantic',)
   
    
class ExampleOpinionForm(Form):
  is_wrong = forms.BooleanField(label=u'Niepoprawny przykład', required=False, initial=False)
  
  def __init__(self, is_wrong=False, 
               *args, **kwargs):
    super(ExampleOpinionForm, self).__init__(*args, **kwargs)
    self.fields['is_wrong'].initial = is_wrong


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):
  # Lemma filters
  lemma = forms.CharField(label=u'Lemat', required=False)
  pos = ModelChoiceField(label=u'Część mowy', queryset=POS.objects.none(), required=False)
  contains_phraseology = ChoiceField(choices=[('', '---------'), ('yes', 'zawiera'), ('no', 'nie zawiera')], 
                                     label=u'Frazeologia', required=False)
  owner = ModelChoiceField(label=u'Właściciel', queryset=User.objects.none(), required=False)
  phraseologist = ModelChoiceField(label=u'Frazeolog', queryset=User.objects.none(), required=False)
  semanticist = ModelChoiceField(label=u'Semantyk', 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_message_from = ModelChoiceField(label=u'Zawiera wiadomość od', queryset=User.objects.none(), 
                                      required=False)
  example_source = ModelChoiceField(label=u'Zawiera 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().order_by('username'), 
                                         required=False)
  # Schema filters
  schema_type = ChoiceField(choices=[('', '---------'), ('normal', 'normalny'), ('phraseologic', 'frazeologiczny')], 
                            label=u'Typ schematu', required=False)
  reflex = ModelChoiceField(label=u'Zwrotność',
                            queryset=Frame_Characteristic.objects.filter(type=u'ZWROTNOŚĆ').order_by('value__priority'), 
                            required=False)
  negativity = ModelChoiceField(label=u'Negatywność', 
                                queryset=Frame_Characteristic.objects.filter(type=u'NEGATYWNOŚĆ').order_by('value__priority'), 
                                required=False)
  predicativity = ModelChoiceField(label=u'Predykatywność', 
                                   queryset=Frame_Characteristic.objects.filter(type=u'PREDYKATYWNOŚĆ').order_by('value__priority'), 
                                   required=False)
  aspect = ModelChoiceField(label=u'Aspekt', 
                            queryset=Frame_Characteristic.objects.filter(type=u'ASPEKT').order_by('value__priority'), 
                            required=False)
  has_argument = forms.CharField(label=u'Zawiera typ frazy', required=False)
  has_position = forms.CharField(label=u'Zawiera pozycję', required=False) 
  schema_opinion = ModelChoiceField(label=u'Opinia o schemacie', queryset=Frame_Opinion_Value.objects.all(), 
                                    required=False)
  filter_frames = forms.BooleanField(label=u'Odfiltruj niepasujące schematy', initial=False,
                                     required=False)
  # Frame filters
  frame_opinion = ModelChoiceField(label=u'Opinia o ramie', queryset=FrameOpinion.objects.order_by('priority'), 
                                   required=False)
  
  def __init__(self, users, phraseologists, semanticists, vocabularies, statuses, senders,
               lemma='.*', sel_pos=None, contains_phraseology=None, 
               sel_user=None, sel_phraseologist=None, sel_semanticist=None,
               sel_vocabulary=None, sel_status=None, sel_schema_type=None,
               sel_reflex=None, sel_negativity=None, sel_predicativity=None, 
               sel_aspect=None, sel_has_argument='.*', sel_has_position='.*',
               sel_schema_opinion=None, can_confirm_example=False, sel_example_source=None, 
               sel_approver=None, sel_sender=None, 
               sel_frame_opinion=None, *args, **kwargs):
    super(FilterForm, self).__init__(*args, **kwargs)
    
    self.fields['pos'].queryset = POS.objects.exclude(tag='unk')
    self.fields['owner'].queryset = users
    self.fields['phraseologist'].queryset = phraseologists
    self.fields['semanticist'].queryset = semanticists
    self.fields['vocabulary'].queryset = vocabularies
    self.fields['status'].queryset = statuses
    self.fields['lemma'].initial = lemma
    self.fields['pos'].initial = sel_pos
    self.fields['contains_phraseology'].initial = contains_phraseology
    self.fields['owner'].initial = sel_user
    self.fields['phraseologist'].initial = sel_phraseologist
    self.fields['semanticist'].initial = sel_semanticist
    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['reflex'].initial = sel_reflex
    self.fields['negativity'].initial = sel_negativity
    self.fields['predicativity'].initial = sel_predicativity
    self.fields['aspect'].initial = sel_aspect
    self.fields['has_argument'].initial = sel_has_argument
    self.fields['has_position'].initial = sel_has_position
    self.fields['schema_opinion'].initial = sel_schema_opinion
    self.fields['has_message_from'].initial = sel_sender
    self.fields['has_message_from'].queryset = senders
    
    self.fields['schema_type'].initial = sel_schema_type
    self.fields['frame_opinion'].initial = sel_frame_opinion

    self.hide_unused_fields()
    
  def hide_unused_fields(self):
    for field_name in self.fields:
      if hasattr(self.fields[field_name], 'queryset') and not self.fields[field_name].queryset.exists():
        self.fields[field_name].widget = forms.HiddenInput()
        
    
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)
  phraseologist_priority = forms.IntegerField(label=u'Frazeolog', required=False, 
                                              widget=forms.TextInput(attrs={'size':'2'}))
  phraseologist_sort_order = ChoiceField(choices=[], label=u'', required=False)
  semanticist_priority = forms.IntegerField(label=u'Semantyk', required=False, 
                                      widget=forms.TextInput(attrs={'size':'2'}))
  semanticist_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,
          phraseologist_order_choice=None, phraseologist_priority_choice=None,
          semanticist_order_choice=None, semanticist_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['phraseologist_sort_order'].choices = order_choices
    self.fields['semanticist_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['phraseologist_sort_order'].initial = phraseologist_order_choice
    self.fields['semanticist_sort_order'].initial = semanticist_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['phraseologist_priority'].initial = phraseologist_priority_choice
    self.fields['semanticist_priority'].initial = semanticist_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())
  pos = ModelMultipleChoiceField(label=u'Część mowy', queryset=POS.objects.exclude(tag=u'unk').order_by('priority'))
  format = ModelChoiceField(label=u'Format wyjściowy', queryset=VocabularyFormat.objects.all())
  frame_opinion = ModelMultipleChoiceField(label=u'Rodzaje schematów', queryset=Frame_Opinion_Value.objects.all())
  lemma_status = ModelMultipleChoiceField(label=u'Statusy haseł', queryset=Lemma_Status.objects.all())
  owner = ModelMultipleChoiceField(label=u'Właściciele', 
                                  queryset=User.objects.filter(lemmas__old=False).distinct().order_by('username'))
  addframeopinion = forms.BooleanField(label=u'Dodaj opinie do formatu tekstowego', required=False, initial=False)

class ManageVocabPermForm(ModelForm):
  editors = ModelMultipleChoiceField(label=u'Edytorzy', queryset = User.objects.order_by('username'))
  viewers = ModelMultipleChoiceField(label=u'Obserwatorzy', queryset = User.objects.order_by('username'))
  
  class Meta:
    model = Vocabulary
    exclude = ('name', )
  
  def __init__(self, editors, viewers, *args, **kwargs):
    super(ManageVocabPermForm, self).__init__(*args, **kwargs)
    self.fields['editors'].initial = [c.pk for c in editors.all()]
    self.fields['viewers'].initial = [c.pk for c in viewers.all()]     
    
#################### Zarzadzanie uzytkownikami ###################################
class UserCreateForm(UserCreationForm):
    group = ModelChoiceField(label=u'Funkcja', queryset=Group.objects.order_by('group_settings__priority'), 
                              required=True)
 
    class Meta:
        model = User
        fields = ("username", 'email', "password1", "password2")
 
        
class ChangeUserFunctionForm(Form):
    user = ModelChoiceField(label=u'Użytkownik', queryset=User.objects.order_by('username'), 
                              required=True)
    group = ModelChoiceField(label=u'Funkcja', queryset=Group.objects.order_by('group_settings__priority'), 
                              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]
   
          
class PropFramesForm(Form):
    start = forms.DateField(initial=datetime.date.today)
    end = forms.DateField(initial=datetime.date.today)


#################### Statystyki argumentow ###################################
class ArgStatsForm(Form):
    arguments = ModelMultipleChoiceField(label=u'Realizacje', queryset = Argument.objects.order_by('text_rep'))
    arg_types = ModelChoiceField(label=u'Typ realizacji', queryset = Argument_Model.objects.order_by('priority'))
    bucket_size = IntegerRangeField(label=u'Wielkość kubełka', required=True, 
                                    min_value=1)
  
    def __init__(self, *args, **kwargs):
        super(ArgStatsForm, self).__init__(*args, **kwargs)
        self.fields['bucket_size'].initial = 50