# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
from festival.models import *
from bestpractices.models import *
from utils import validateEmail
from forms import MeetingCommentForm
import random
try:
  import json
except:
  import simplejson as json
from django.core.mail import send_mail
from settings import ERANG_SUBSCRIBE_URL
import urllib2

def index(request):
  index_data = {}
  new_meetings = MeetingDay.objects.all().order_by('-meeting_date')[:5]   # get 5 latest meetings
  projects = Project.objects.all().order_by('start_date')

  index_data['latest_meetings'] = new_meetings
  index_data['projects'] = projects

  return render_to_response("festival_index.html", { 'data' : index_data })


def meeting_details(request, meeting_id):
  meeting_data = {}
  meeting_data['meeting'] =  get_object_or_404(Meeting, id=meeting_id)
#  meeting_data['sessions'] =  Session.objects.filter(day__meeting__id=meeting_id) # get meetings session objs
  meeting_data['talks'] = Talk.objects.filter(session__day__meeting__id=meeting_id)
  meeting_data['images'] = Image.objects.filter(meeting__id=meeting_id)
  meeting_data['sessions'] = Session.objects.filter(day__meeting__id=meeting_id).order_by("day").order_by("session_no")
  meeting_data['documents'] = Document.objects.filter(meeting__id=meeting_id).exclude(talk__isnull=False)
  meeting_data['comments'] = Comment.objects.filter(meeting__id=meeting_id).exclude(is_displayed=False)
  captcha_length = CommentCaptcha.objects.all().count()
  random_captcha = random.randint(1,captcha_length)
  captcha = CommentCaptcha.objects.get(pk=random_captcha)
  captcha_d = {
    'question': captcha.question,
    'id': captcha.id
    }
  
  for s in meeting_data['sessions']:
    s.talks = Talk.objects.select_related('image', 'audio', 'document').filter(session__id=s.id)
    for t in s.talks:
      t.images = Image.objects.filter(talk__id=t.id)
      t.documents = Document.objects.filter(talk__id=t.id)
      t.audio = Audio.objects.filter(talk__id=t.id)
      t.video = Video.objects.filter(talk__id=t.id)

  meeting_data['imagegallery'] = Image.objects.filter(meeting__id=meeting_id)
  meeting_data['participants'] = Participant.objects.filter(meeting__id=meeting_id).order_by('name')
  comment_form = MeetingCommentForm()
  return render_to_response("meeting.html", { 'data' : meeting_data, 'comment_form': comment_form, 'id': meeting_id, 'captcha': captcha_d })

def meetings(request):
  meetings = list(Meeting.objects.all())
  for m in meetings:
    m.dates = MeetingDay.objects.filter(meeting__id=m.id).order_by('-meeting_date')
    m.end_date = m.dates[0].meeting_date
    m.start_date = m.dates[len(m.dates) - 1].meeting_date

  meetings.sort(sort_meetings)

  return render_to_response("meetings.html", {'meetings': meetings})


def meeting_comment(request):
  if request.GET.has_key('captcha') and request.is_ajax():
    captcha_answer = str(request.GET['captcha']).strip()
    captcha_id = int(request.GET['captcha_id'])
    captcha_obj = CommentCaptcha.objects.get(pk=captcha_id)
    correct_answer = str(captcha_obj.answer).strip()
#    print captcha_answer.lower + " " + correct_answer
    if correct_answer.lower() != captcha_answer.lower():
      r = {
        'status': 0,
        'msg': 'Please answer the question in the box correctly. Thanks.'
        }
    else:
      comment_form = MeetingCommentForm(request.GET)
      if comment_form.is_valid():
        c = comment_form.save(commit=False)
        meeting_id = int(request.GET['meeting_id'])
        meeting_obj = Meeting.objects.get(pk=meeting_id)
        c.meeting = meeting_obj
        c.save()
        r = {
          'status': 1,
          'msg': 'Comment saved.'
          }
      else:
      #TODO: Pass validation errors properly accessing form.errors
        r = {
          'status': 0,
          'msg': 'Please enter a valid email address. We will never display it publicly, sell it, or use it to send you unsolicited email. Thanks.'
          }  
  else:
    r = {
      'status': 0,
      'msg': 'Please answer the question in the box correctly. Thanks.'
      }      
  return HttpResponse(json.dumps(r), mimetype="application/json")

def sort_meetings(m1, m2):
  if m1.start_date < m2.end_date:
    return 1
  else:
    return -1

def wireframe(request):
  return render_to_response("festival_wireframe.html")

def erang(request):
  return render_to_response("erang.html")

def publications(request):
  return render_to_response("publications.html")

def surveys(request):
  return render_to_response("surveys.html")

def home(request):
  return render_to_response("home.html")


def projects(request):
  projects = Project.objects.all();
  return render_to_response("projects.html", {'projects': projects})

def resources(request):
  resources = Document.objects.filter(is_resource=True).order_by('title')
  return render_to_response("resources.html", {'resources': resources})

def people(request):
  participants = Participant.objects.all().order_by('name')

  l = []
  l2 = []
  for p in participants:
    if p.name in l:
      pass
    else:
      l.append(p.name)
      l2.append(p)

  participants = l2

  return render_to_response("people.html", {'participants': participants})


def project(request, project_id):
  project = get_object_or_404(Project, id=project_id)
  return render_to_response("project.html", {'project': project})

def save_email(request):
  email = request.GET['email']
  if validateEmail(email):
    t = Signup(email=email)
    t.save()
    erang_subscribe_url = ERANG_SUBSCRIBE_URL + "email"
    subscribed = urllib2.urlopen(erang_subscribe_url).read()
    return HttpResponse("1")
  else:
    return HttpResponse("0")

def email_signups(request):
  to_emails = ['sanjaybhangar@gmail.com']
  arr = []
  for s in Signup.objects.all():
    arr.append(s.email)
  eml_list = "\n".join(arr)
  message_pre = "Someone pinged http://theatreforum.in/emailsharvarialltheemails/ , so here it is: \n\n" 
  message = message_pre + eml_list 
  send_mail("List of Signups on theatreforum.in", message, 'do_not_reply@theatreforum.in', to_emails, fail_silently=False)
  return HttpResponse("ok")

def video(request, video_id):
  video = get_object_or_404(Video, id=video_id)
  return render_to_response("video.html", {'video': video})

def bestpractices(request):
  return render_to_response("bestpractices.html", {
    'downloads': BestPracticeDownload.objects.all()
  })

def bpguidelines(request):
  return render_to_response("bpguidelines.html", {
    'guidelines': Guideline.objects.all()
  })

def bpstories(request):
  stories = []
  for bp in BestPractice.objects.all():
    stories.append({
      'id': bp.id,
      'title': bp.title
    })
  return render_to_response("bpstories.html", {
    'stories': stories
  })

def bpglossary(request):
  return render_to_response("bpglossary.html", {
    'terms': Glossary.objects.all()
  })

def bpstory(request, story_id):
  story_dict = BestPractice.objects.get(pk=story_id).info_dict()
  return render_to_response("bpstory.html", story_dict)

def bpguideline(request, guideline_id):
  guideline_dict = Guideline.objects.get(pk=guideline_id).get_dict()
  return render_to_response("bpguideline.html", guideline_dict)
  
def bpfaq(request):
  faqs = BestPracticeFAQ.objects.all()
  return render_to_response("bpfaq.html", {
    'faqs': faqs
  })

def bpdownload(request):
  return render_to_response("bpdownload.html")

