# Create your views here.
from models import *
from forms import *
from django.shortcuts import render_to_response, get_object_or_404
from ox.django.shortcuts import render_to_json_response
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.mail import send_mail
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime

def person_form(request):
    person = Person.objects.all()[0]
    form = PersonForm(instance=person)
    inlines = [inline(instance=person) for inline in form.inlines]
    #import pdb
    #pdb.set_trace()
    return render_to_response("test/person_form.html", {'form': form, 'inlines': inlines})

@login_required
def edit_profile(request):
    user = request.user
    person = Person.objects.get(user=user)
    
    #person = Person.objects.all()[0]
    if request.POST:
        form = PersonForm(request.POST, request.FILES, instance=person)
        inlines = [inline(request.POST, request.FILES, instance=person) for inline in form.inlines]
        if form.is_valid():
            instance = form.save()
            form.save()
            all_valid = True
            for inline in inlines:
                if inline.is_valid():
                    inline.save()
                else:
                    all_valid = False
            if all_valid:
                return HttpResponseRedirect("/edit_profile/")

    else:
        form = PersonForm(instance=person)
        inlines = [inline(instance=person) for inline in form.inlines]
    
    context = RequestContext(request, {
        'form': form,
        'inlines': inlines
    })
    return render_to_response("test/person_form.html", context)

@csrf_exempt
@login_required 
def friend_invite(request):
    if request.method == 'POST':
        form = PersonForm(request.POST, request.FILES)
        if form.is_valid():
            invitee = form.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()
            #try:
            invitation.send_invite()
            #except:
            #    return HttpResponse("<html><body>Not Invited!!</body></html>")            
            return HttpResponse("<html><body>Invited!!</body></html>")            
            
            #return HttpResponseRedirect('/invitation/invite/')
        else:
            context = {'form': form}
            return render_to_response('test/popup.html', context)

    else:
        form = PersonForm()            
        context = RequestContext(request, {
                'form': form
                })
        return render_to_response("test/popup.html", context)


def invitation_accept(request,invite_code):
    invitee = get_object_or_404(PersonInvitation, invite_code__exact=invite_code).invitee
    request.session['invite_code'] = invite_code
    request.session['invitee_first_name'] = invitee.first_name
    request.session['invtee_last_name'] = invitee.last_name
    request.session['invitee_email'] = invitee.email
    return HttpResponseRedirect('/accounts/signup')



def personpopup(request):
    form = PersonForm()
    if request.POST:
        return HttpResponse("<script>opener.dismissAddAnotherPopup(window, '%s', '%s')</script>" % ("45", "sanjay bhangar",))
        form = PersonForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save()
            #return HttpResponse("<html><body>This person will be Invited!</body></html>")            
            #return HttpResponse("<script>opener.dismissAddAnotherPopup(this, '%s', '%s')</script>" % (str(instance.id), instance.get_title()))
    else:
        form = PersonForm()
    context = RequestContext(request, {
        'form': form
    })
    return render_to_response("test/popup.html", context)



def autocomplete(request):
    q = request.GET.get('q', 'a')
    page = int(request.GET.get('page', '1'))
    page_limit = int(request.GET.get('page_limit', '10'))
    #qset_all = Person.objects.all()
    qset = Person.objects.filter(first_name__icontains=q)
    paginator = Paginator(qset, page_limit)
    results = paginator.page(page)
    items = [{'id': obj.id, 'first_name': obj.first_name, 'last_name': obj.last_name, 'about': obj.about, 'text': obj.first_name + " " + obj.last_name} for obj in results.object_list]
    return render_to_json_response({
        'items': items,
        'has_next': results.has_next()
    })
                                


def grouppopup(request):
    form = PersonForm()
    if request.POST:
        return HttpResponse("<script>opener.dismissAddAnotherPopup(window, '%s', '%s')</script>" % ("45", "sanjay bhangar",)) 
        form = PersonForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save()
#            return HttpResponse("<script>opener.dismissAddAnotherPopup(this, '%s', '%s')</script>" % (str(instance.id), instance.get_title()))
    else:
        form = PersonForm()
    context = RequestContext(request, {
        'form': form
    })
    return render_to_response("test/popup.html", context)


def contact_person(request):
    frm = request.user.email
    to_person = request.GET.get("to", None)
    try:
        to = Person.objects.get(pk=to_person)
    except:
        return HttpResponse("An error occurred. Please contact contact@theatreforum.in and let us know. Thanks.")
    message = request.GET.get("message", None)
    if not message:
        return HttpResponse("Please enter a message.")
    if not to.user:
        return HttpResponse("Sorry, person does not have an email address associated on the site.")
    else:
        to_email = to.user.email
        send_mail("Contact on theatreforum.in", message, frm, [to_email])
        return HttpResponse("Your message has been sent, thanks.")
    
        

def contact_group(request):
    frm = request.user.email
    to_group = request.GET.get("to", None)
    try:
        to = TheatreGroup.objects.get(pk=to_group)
    except:
        return HttpResponse("An error occurred. Please contact contact@theatreforum.in and let us know. Thanks.")
    message = request.GET.get("message", None)
    if not message:
        return HttpResponse("Please enter a message.")
    if not to.added_by:
        return HttpResponse("Sorry, group does not have an email address associated on the site.")
    else:
        #FIXME: also get email addresses of all group admins
        to_email = to.added_by.email
        send_mail("Contact on theatreforum.in", message, frm, [to_email])
        return HttpResponse("Your message has been sent, thanks.")
    

