import datetime
import re
import time

from django.contrib.auth import authenticate
from django.contrib.auth import login, logout
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import Context
from django.template import RequestContext
from django.template import loader
from django.utils.translation import gettext_lazy as _

from conference.forms import ParticipantForm, LoginForm
from conference.models import Participant


def makemsg(username,url):
  """
  Email body to be sent to user.
  """
  msg = _("\
Dear %(username)s,\n\n\
\
Thank you for registering with us. Please visit this url:\n\n\
%(url)s\n\n\
to complete the registration\n\n\
regards\n\
PyCon India 2009 Team\
") %{'username': username,'url': url}
  return msg
  
def home(request, template_name='home.html'):
  if request.user.is_authenticated():
    return render_to_response(template_name, RequestContext(request, {}))
  if request.method == 'POST':
    user_form = LoginForm(request.POST)
    if user_form.is_valid():
      username = request.POST['username']
      password = request.POST['password']
      user = authenticate(username=username, password = password)
      if user is not None:
        login(request, user)
        return render_to_response(template_name, RequestContext(request, {}))
  else:
    user_form = LoginForm()
  return render_to_response(template_name,
                            {'form': user_form},
                            RequestContext(request)
                              )
  
def logout_view(request):
  #print request.user.username
  if request.user.is_authenticated():
    #print request.user.username
    logout(request)		
  return HttpResponseRedirect('../')
	
def register(request):
  """Register function.
  """

  if request.user.is_authenticated():
    msg = _("You are already registered")
    return HttpResponseRedirect("/2009/message/%s/" % msg)

  if request.POST:
    # On POST method.
    form = ParticipantForm(request.POST)
    if form.is_valid():
      # If form is clean and has no errors.
      fm = form.cleaned_data
      if len(fm['username']) > 30 or len(fm['username']) < 4:
        # Username should be > 4 characters and less that 30 characters.
        form.errors['username']=[_("User Name must be 4-30 characters long")]
      else:
        r = re.compile(r"[A-Za-z0-9_]")
        for alph in fm['username']:
          # Check if every character of the username is either an 
          # alphabet or numeral.
          if  not r.match(alph):
            form.errors['username']=[_("Invalid character %s in Username") %(alph)]
        if not form.errors:
          test = User.objects.filter(username__iexact=fm['username'])
          # Check if username already exists.
          if test:
            form.errors['username'] = [("Username registered, try something else")]          
          # Check if the email id has already been in use.
          teste = User.objects.filter(email__iexact=fm['email'])
          if teste:
            form.errors['email'] = [_("Email registered. Try something else")]
          else:
            # If username is found in the temporary registration database
            # then show pending error message.
            teste1 = User.objects.filter(email__iexact=fm['email'])
            if teste1:
              form.errors['email'] = [("Username pending registration. Try tomorrow")]
    if not form.errors:
      # If all goes well then push into database.
      new_reg = form.save()      
      #new_reg.save()      
      return HttpResponseRedirect("/regthank/%i/" % new_reg.id)
  else:
    # On the GET method.
    form = ParticipantForm()
  return render_to_response("register.html",
      { "form":form, }, context_instance=RequestContext(request))


def regthank(request,id):
    """Function displayed after registration is successful.
    """
    p = Participant.objects.get(pk=id)
    t = loader.get_template("regthank.html")
    c = RequestContext(request,
                {"p":p,
                 })
    return HttpResponse(t.render(c))
