import random

from django.db import IntegrityError
from django.http import Http404
from django.utils.datastructures import MultiValueDictKeyError

from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate

from django.shortcuts import redirect, render_to_response

from offline.event.models import Event

from offline.quiz.utils import gen_key
from offline.quiz.models import Profile, QuestionBank, Quiz, Answer
from offline.quiz.forms import UserRegisterForm

def start_page(request):
    """ first see if user is authenticated.
    If he is, redirect to the page where quiz happens.
    Else register the user
    """

    try:
        event = Event.objects.all()[0]
    except IndexError:
        raise Http404
    
    if event.quiz_status == '00':
        raise Http404

    user = request.user
    if user.is_authenticated():
        return redirect("/quiz/start/")
    else:
        try:
            ip = request.META['REMOTE_ADDR']
            Quiz.objects.get(user_ip=ip, quiz_num=event.quiz_status)
            return redirect("/quiz/complete")
        except Quiz.DoesNotExist:
            pass

    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data

            while True:
                try:
                    username = gen_key(20)
                    new_user = User.objects.create_user(username, "temp@temp.com", "123")
                    break
                except IntegrityError:
                    pass

            new_user.first_name = data['first_name']
            new_user.last_name = data['last_name']
            new_user.save()

            new_profile = Profile(user=new_user)
            new_profile.profession = data['profession']
            new_profile.affiliated_to = data['affiliated_to']
            new_profile.save()

            user = authenticate(username=username, password="123")
            login(request, user)
            return redirect("/quiz/start/")

        else:
            return render_to_response('register.html',{'form':form})
    else:
        form = UserRegisterForm()
        return render_to_response('register.html',{'form':form})

def start_quiz(request):
    """ get the user by his username.
    then check for the event quiz status
    then check if his ip has finished the quiz
    then make his quiz paper and redirect to the right question.
    """

    user = request.user

    try:
        event = Event.objects.all()[0]
    except IndexError:
        raise Http404

    if event.quiz_status == "00":
        raise Http404

    try:
        old_quiz = Quiz.objects.get(event=event,user=user, quiz_num=event.quiz_status)
        return redirect("/quiz/answer/%s"%(old_quiz.key))
    except Quiz.DoesNotExist:
        ip = request.META['REMOTE_ADDR']
        key = gen_key(10)
        new_quiz = Quiz(event=event, user=user, quiz_num=event.quiz_status, user_ip=ip, key=key)

        available_que_ids = [ str(_.id) for _ in QuestionBank.objects.filter(quiz_num=event.quiz_status) ]
        random.shuffle(available_que_ids)
        new_quiz.que_remaining = "|".join(available_que_ids)
        new_quiz.save()

        return redirect("/quiz/intro/%s"%(new_quiz.key))

def quiz_intro(request, quiz_key):
    """ simply give intro to user
    if there are questions redirect.
    else raise Http404
    """

    user = request.user

    try:
        event = Event.objects.all()[0]
    except IndexError:
        raise Http404

    if event.quiz_status == "00":
        raise Http404

    try:
        old_quiz = Quiz.objects.get(event=event,user=user, quiz_num=event.quiz_status)
        return render_to_response("quiz_intro.html", {"user":user, "quiz":old_quiz}) 
    except Quiz.DoesNotExist:
        raise Http404

def answer(request, quiz_key):
    """ see if username and quiz give a proper quiz object
    then see if there are any available questions
    then render the proper question.
    """

    user = request.user
    if not user.is_authenticated():
        raise Http404

    try:
        event = Event.objects.all()[0]
    except IndexError:
        raise Http404

    if event.quiz_status == "00":
        raise Http404

    try:
        quiz = Quiz.objects.get(event=event,user=user,key=quiz_key)
    except Quiz.DoesNotExist:
        raise Http404

    remaining_que = quiz.que_remaining.split('|')
    if not remaining_que:
        raise Http404
    
    que_id = remaining_que[0]
    question = QuestionBank.objects.get(id=que_id)
    if request.method == "POST":
        try:
            answer = request.POST['answer']
        except MultiValueDictKeyError:
            answer = ""
        new_answer = Answer(question=question)
        new_answer.submitted_ans = answer.strip()
        new_answer.save()

        quiz.que_answered.add(new_answer)
        remaining_que.remove(que_id)
        quiz.que_remaining = "|".join(remaining_que)
        quiz.key = gen_key(10)
        quiz.save()

        if not remaining_que:
            return redirect('/quiz/complete')
        else:
            return redirect('/quiz/answer/%s'%quiz.key)
    else:
        options = [ _.strip() for _ in question.options.split('\n') ] if question.options else []
        return render_to_response('display_question.html', {'question':question, 'options':options})

def quiz_complete(request):
    """ display thanq and log the user out.
    """

    user = request.user
    logout(request)
    return render_to_response("quiz_complete.html")
