# Path: narwhal/plugins/user/invite/models.py
# class Invite(Model):
#     inviter = ForeignKey('auth.User', verbose_name=_('inviter'), related_name='invites_sent')
#     invitee = OneToOneField('auth.User', null=True, blank=True, verbose_name=_('invitee'), related_name='invite_recieved')
#     email_address = CharField(_('email address'), max_length='100')
#     code = CharField(_('invite_code'), max_length=32, unique=True, default=lambda: md5(os.urandom(32)).hexdigest())
# 
# Path: narwhal/plugins/user/invite/forms.py
# class InviteForm(BootstrapForm):
#     
#     email_address = EmailField()
# 
# Path: narwhal/core/profile/forms.py
# class SignupForm(BootstrapForm):
#     username        = CharField(max_length=80)
#     password        = CharField(max_length=80)
#     password_repeat = CharField(max_length=80)
# 
#     def clean_username(self):
#         username = self.cleaned_data['username']
#         if User.objects.filter(username__iexact=username).exists():
#             raise ValidationError(_('Username already in use. Please try another.'))
# 
#     def clean_password(self):
#         password = self.cleaned_data['password']
#         if password.length() < PASSWORD_MINIMUM_LENGTH:
#             raise ValidationError(_('Password to short. Must be at least %i digits long.')%PASSWORD_MINIMUM_LENGTH)
#         return password
# 
#     def clean_password_repeat(self):
#         password = self.cleaned_data.get('password')
#         password_repeat = self.cleaned_data.get('password_repeat')
#         
#         if password and password != password_repeat:
#             raise ValidationError(_('Passwords do not match.'))
#         return password_repeat


from django.conf import settings
from django.template import loader
from django.forms.util import ErrorList
from django.views.generic import FormView
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.template.context import RequestContext
from django.core.mail import send_mail, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.decorators import login_required
from .models import Invite
from .forms import InviteForm
from django.contrib.auth.models import User
from narwhal.core.profile.forms import SignupForm
class InviteUser(FormView):
    template_name = 'send_invite.html'
    form_class = InviteForm
    success_url = reverse('invite-sent')
        
    def form_valid(self, form):
        invite = Invite(inviter = self.request.user, email_address = form.cleaned_data['email_address'])
        message = EmailMessage(subject=_('You have been invited to join %(site_name)s by %(user).') %\
                                            {'site_name': settings.SITE_NAME, 'user': invite.invitee.username },
                               body = loader.get_template("invite_email.html").render(RequestContext({'invite':invite})),
                               to = invite.email_address)
        
        try:
            message.send()
            invite.save()
            return HttpResponseRedirect(self.success_url)
        
        except: 
            form.errors += ErrorList(['Could not send email to that address.'])
            return self.form_invalid(form)

class SignupFromInvite(FormView):
    template_name = 'send_invite.html'
    form_class = SignupForm
    success_url = reverse('login')
    
    def get(self, request, *args, **kwargs):
        
        try:
            self.invite = Invite.objects.get(invitee__exact=None, code = request.GET['key'])

# Path: narwhal/plugins/user/invite/models.py
# class Invite(Model):
#     inviter = ForeignKey('auth.User', verbose_name=_('inviter'), related_name='invites_sent')
#     invitee = OneToOneField('auth.User', null=True, blank=True, verbose_name=_('invitee'), related_name='invite_recieved')
#     email_address = CharField(_('email address'), max_length='100')
#     code = CharField(_('invite_code'), max_length=32, unique=True, default=lambda: md5(os.urandom(32)).hexdigest())
# 
# Path: narwhal/plugins/user/invite/forms.py
# class InviteForm(BootstrapForm):
#     
#     email_address = EmailField()
# 
# Path: narwhal/core/profile/forms.py
# class SignupForm(BootstrapForm):
#     username        = CharField(max_length=80)
#     password        = CharField(max_length=80)
#     password_repeat = CharField(max_length=80)
# 
#     def clean_username(self):
#         username = self.cleaned_data['username']
#         if User.objects.filter(username__iexact=username).exists():
#             raise ValidationError(_('Username already in use. Please try another.'))
# 
#     def clean_password(self):
#         password = self.cleaned_data['password']
#         if password.length() < PASSWORD_MINIMUM_LENGTH:
#             raise ValidationError(_('Password to short. Must be at least %i digits long.')%PASSWORD_MINIMUM_LENGTH)
#         return password
# 
#     def clean_password_repeat(self):
#         password = self.cleaned_data.get('password')
#         password_repeat = self.cleaned_data.get('password_repeat')
#         
#         if password and password != password_repeat:
#             raise ValidationError(_('Passwords do not match.'))
#         return password_repeat


# Path: narwhal/plugins/user/invite/views.py
from django.conf import settings
from django.template import loader
from django.forms.util import ErrorList
from django.views.generic import FormView
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.template.context import RequestContext
from django.core.mail import send_mail, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.decorators import login_required
from .models import Invite
from .forms import InviteForm
from django.contrib.auth.models import User
from narwhal.core.profile.forms import SignupForm

class InviteUser(FormView):
    template_name = 'send_invite.html'
    form_class = InviteForm
    success_url = reverse('invite-sent')
        
    def form_valid(self, form):
        invite = Invite(inviter = self.request.user, email_address = form.cleaned_data['email_address'])
        message = EmailMessage(subject=_('You have been invited to join %(site_name)s by %(user).') %\
                                            {'site_name': settings.SITE_NAME, 'user': invite.invitee.username },
                               body = loader.get_template("invite_email.html").render(RequestContext({'invite':invite})),
                               to = invite.email_address)
        
        try:
            message.send()
            invite.save()
            return HttpResponseRedirect(self.success_url)
        
        except: 
            form.errors += ErrorList(['Could not send email to that address.'])
            return self.form_invalid(form)

class SignupFromInvite(FormView):
    template_name = 'send_invite.html'
    form_class = SignupForm
    success_url = reverse('login')
    
    def get(self, request, *args, **kwargs):
        
        try:
            self.invite = Invite.objects.get(invitee__exact=None, code = request.GET['key'])

        except KeyError, Invite.DoesNotExist: