import floppyforms as forms
from registration.forms import RegistrationForm
from models import *
from registration.models import RegistrationProfile
import json

from padmavideos.models import PadmaVideo, PadmaClip
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.contrib.contenttypes.models import ContentType
from app.forms import *
from imagestore.forms import AlbumForm, ImageForm
from itfprofiles.models import * 
from scriptbank.models import Script
#Forms and Inlines for Generic Classes
from events.models import Event
#class AlbumInlineForm(ItfForm, AlbumForm):
#    pass

#class ImageInlineForm(ItfForm, ImageForm):
#    pass

class LocationForm(ItfForm):

    class Meta:
        model = Location
        #fields = ('city','address', 'pincode')
        exclude = ('lat', 'lon',)

LocationsInline = itf_inlineformset_factory(Location, form=LocationForm, title="Locations", is_generic=True)

class BuzzItemsForm(ItfForm):

    class Meta:
        model = BuzzItem
        
BuzzItemsInline = itf_inlineformset_factory(BuzzItem, form=BuzzItemsForm, title="Buzz Items", is_generic=True)


class AwardsForm(ItfForm):

    class Meta:
        model = Award

AwardsInline = itf_inlineformset_factory(Award, form=AwardsForm, title="Awards", is_generic=True)

class ResourcesForm(ItfForm):

    class Meta:
        model = Resource

ResourcesInline = itf_inlineformset_factory(Resource, form=ResourcesForm, title="Resources", is_generic=True)


class TrainingsForm(ItfForm):

    class Meta:
        model = Training

TrainingsInline = itf_inlineformset_factory(Training, form=TrainingsForm, title='Training', is_generic=True)


class PadmaClipForm(ItfForm):
    pass

    class Meta:
        model = PadmaClip

PadmaClipsInline = itf_inlineformset_factory(PadmaClip, extra=1, is_generic=True, form=PadmaClipForm, title="Videos")


class EventsInlineForm(ItfForm):
    parent_event = forms.ModelChoiceField(Event.objects.all(), widget=AutocompleteAddWidget(model_class=Event))

    class Meta:
        model = Event
        exclude = ('people', 'groups', 'event_type',)
        widgets = {
            'start_date': forms.DateInput,
            'end_date': forms.DateInput,
            'start_time': forms.TimeInput,
            'end_time': forms.TimeInput
        }

EventsInline = itf_inlineformset_factory(Production, Event, extra=2, form=EventsInlineForm, title="Performances", is_generic=False)

#AlbumsInline = itf_inlineformset_factory(Album, extra=1, is_generic=True, form=AlbumInlineForm, title="Photo Albums")


#Popup Form Classes:
class PopupPersonForm(PopupForm):        

    def save(self, *args, **kwargs):
        if kwargs.has_key('request'):
            request = kwargs.pop('request')
            #form = PersonForm(request.POST, request.FILES)
            
            invitee = super(PopupPersonForm, self).save(*args, **kwargs)
            invitee.save()
            invitation = PersonInvitation(
                invitee=invitee,
                invite_code=User.objects.make_random_password(30),
                is_validated=False,
                inviter=Person.objects.get(user=request.user),
                sent_date=datetime.now()                
                )

            invitation.save()
            #import pdb
            #pdb.set_trace()
            invitation.send_invite()

            return invitee


    class Meta:
        model = Person
        fields = ('first_name', 'last_name', 'email',)


class PopupGroupForm(PopupForm):

    class Meta:
        model = TheatreGroup
        fields = ('name', 'email',)


class PopupProductionForm(PopupForm):
    group = forms.ModelChoiceField(TheatreGroup.objects.all(), widget=AutocompleteAddWidget(model_class=TheatreGroup))

    class Meta:
        model = Production
        fields = ('name', 'group',)


#Inline form definitions and inlines for Person form
class PersonOccupationForm(ItfForm):
    
    class Meta:
        model = PersonOccupation

class ConnectionsForm(ItfForm):
    #ctype = ContentType.objects.get_for_model(Person)
    person2 = forms.ModelChoiceField(Person.objects.all(), widget=AutocompleteAddWidget(model_class=Person))
    
    class Meta:
        model = PersonPerson
        exclude = ('disapproved',)

class PersonProductionForm(ItfForm):
    production = forms.ModelChoiceField(Production.objects.all(), widget=AutocompleteAddWidget(model_class=Production))
    
    class Meta:
        model = PersonProduction

class TheatreGroupProductionForm(ItfForm):
    #j pass an empty list,
    #production = forms.ModelChoiceField([], widget=AutocompleteAddWidget(model_class=Production))   
    
    class Meta:
        model = Production

ProductionsTheatreGroupInline = itf_inlineformset_factory(TheatreGroup, Production, form=TheatreGroupProductionForm, extra=1, title="Productions")

class PersonGroupForm(ItfForm):
    group = forms.ModelChoiceField(TheatreGroup.objects.all(), widget=AutocompleteAddWidget(model_class=TheatreGroup))

    class Meta:
        model = PersonGroup

ConnectionsInline = itf_inlineformset_factory(Person, PersonPerson, fk_name='person1', form=ConnectionsForm, extra=1, title="Add / Edit Connections", help_text="select the people you are connected with and how you are related in the theatre world")
ProductionsInline = itf_inlineformset_factory(Person, PersonProduction, form=PersonProductionForm, extra=1, title="Productions you have worked in")

GroupsInline = itf_inlineformset_factory(Person, PersonGroup, extra=1, form=PersonGroupForm, title="Theatre groups you are a part of or have worked with")
PersonOccupationsInline = itf_inlineformset_factory(Person, PersonOccupation, extra=1, form=PersonOccupationForm, title="Select your occupation / you can add as many as you like")


#Actual person form definition
class PersonForm(ItfForm):
#    occupations = forms.ModelMultipleChoiceField(Occupation.objects.all(), widget=forms.CheckboxSelectMultiple())
#    connections = forms.ModelMultipleChoiceField(Person.objects.all(), widget=ConnectionsWidget())
#    occupations = forms.ModelMultipleChoiceField(Occupation.objects.all(), widget=forms.CheckboxSelectMultiple())
    email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'example@email.com'}))
#    inlines = [ConnectionsInline]   
    inlines = [PersonOccupationsInline, ConnectionsInline, ProductionsInline, GroupsInline, TrainingsInline, BuzzItemsInline, AwardsInline, ResourcesInline, PadmaClipsInline]

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.add_input(Submit('submit', 'Submit'))
        super(PersonForm, self).__init__(*args, **kwargs)


    class Meta:
        exclude = ('connections', 'productions', 'groups', 'last_accessed', 'occupations',)
        model = Person
        widgets = {
            'first_name': forms.TextInput,
            'last_name': forms.TextInput,
            'languages': forms.CheckboxSelectMultiple,
            'dob': forms.DateInput
#            'occupations': forms.CheckboxSelectMultiple
        }
        #exclude = ('connections', 'productions', 'occupations', 'groups',)


#Inline definitions and form for TheatreGroup      
class GroupPersonForm(ItfForm):
    person = forms.ModelChoiceField(Person.objects.all(), widget=AutocompleteAddWidget(model_class=Person)) 

    class Meta:
        model = PersonGroup

class GroupOccupationForm(ItfForm):
    
    class Meta:
        model = GroupGroupOccupation


PersonGroupInline = itf_inlineformset_factory(TheatreGroup, PersonGroup, form=GroupPersonForm, title="People in the Group")

GroupOccupationInline = itf_inlineformset_factory(TheatreGroup, GroupGroupOccupation, form=GroupOccupationForm, title="Nature of work for the group") 


class TheatreGroupForm(ItfForm):
    languages = forms.ModelMultipleChoiceField(Language.objects.all(), widget=forms.CheckboxSelectMultiple())
    inlines = [GroupOccupationInline, PersonGroupInline, ResourcesInline, BuzzItemsInline, AwardsInline, TrainingsInline, LocationsInline, ProductionsTheatreGroupInline]

    class Meta:
        model = TheatreGroup
        exclude = ('added_by', 'locations', 'nature_of_work',)



#Inline definitions and form for Production
class PersonProductionForm(ItfForm):
    person = forms.ModelChoiceField(Person.objects.all(), widget=AutocompleteAddWidget(model_class=Person)) 

    class Meta:
        model = PersonProduction

PersonProductionInline = itf_inlineformset_factory(Production, PersonProduction, form=PersonProductionForm, title="People associated with the production")

class ProductionForm(ItfForm):
    inlines = [PersonProductionInline, AwardsInline, EventsInline]
    script = forms.ModelChoiceField(Script.objects.all(), widget=AutocompleteAddWidget(model_class=Script))  
    languages = forms.ModelMultipleChoiceField(Language.objects.all(), widget=forms.CheckboxSelectMultiple())
    director = forms.ModelChoiceField(Person.objects.all(), widget=AutocompleteAddWidget(model_class=Person))     
    playwright = forms.ModelChoiceField(Person.objects.all(), widget=AutocompleteAddWidget(model_class=Person)) 
    group = forms.ModelChoiceField(TheatreGroup.objects.all(), widget=AutocompleteAddWidget(model_class=TheatreGroup))
    class Meta:
        model = Production
        exclude = ('added_by',)
        widgets = {
            'debut_date': forms.DateInput
        }


#Registration forms / not connected to Itf Profiles
class ItfAllAuthRegForm(forms.Form):
    firstname=forms.CharField()
    lastname=forms.CharField()
    #invite_code=forms.HiddenField()
    
    #def __init__(self, request=None):
        
        
    
    def save(self, user, request=None):
        first_name = self.cleaned_data['firstname']
        last_name = self.cleaned_data['lastname']
        if request.session.has_key('invite_code'):
            invite_code = request.session['invite_code']
            pi = PersonInvitation.objects.get(invite_code=invite_code)
            inviter = pi.inviter
            invitee = pi.invitee
            invitee.user=user
            invitee.save()
        else:        
            p = Person(user=user, first_name=first_name, last_name=last_name, email=user.email)
            p.save()
        user.first_name = first_name
        user.last_name = last_name
        user.save()
        return self


class ItfRegistrationForm(RegistrationForm):
    subscribe = forms.BooleanField(help_text='Subscribe to newsletter?')

    def save(self, profile_callback=None):
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'])
        new_profile = ItfProfile(user=new_user, subscribed=self.cleaned_data['subscribe'])
        new_profile.save()
        return new_user
