###########################################################################
#
#   File Name      Date          Owner            Description
#   ----------    -------      ----------       ----------------
#   views.py      8/20/2014   Archana Bahuguna  View fns for qzngn APIs
#
#  Handles HTTP requests for a qzengine using Flask/SQLAlchemy. 
#  Flask session, basic authentication, role (admin/user permisions) are 
#  implemented , Flask bcrypt is used for password encryption.
#  Jinja templatig is used for ui of web app
#
###########################################################################

import os, logging
from flask import Flask, request, render_template, make_response
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
import models 
import utls 
import logs 

app = Flask(__name__)
bcrypt = Bcrypt(app)

@app.route('/quizzes/<int:qzid>/questions', methods = ['GET', 'POST'])
def qz_questions(qzid):
    """ Class that defines methods for processing get/post requests 
        for /api/quizzes endpoint 
    """

    # GET /quizzes/qzid/questions
    if request.method == 'GET':
        error = None
        """Get all quiz questions"""
        logs.debug_ ("_______________________________________________")
        logs.debug_ ("QuizzesAPI get fn: %s" %(request))

        # Query from quiz table
        # Get qzid from query string parameters of get request
        # In this case just create default?

        # Query Question table
        #Arch: modify query to get all questions
        ques = models.Question.query.join(models.Anschoice).filter\
                         (models.Question.qzid == qzid).all()


        # Return response
        return render_template('questions.html', ques=ques, error=error)
    
    #POST /quizzes/qzid/questions
    else:
        error = None
        """ Get answers to all quiz questions"""
        logs.debug_ ("_______________________________________________")
        logs.debug_ ("QuizzesAPI Post fn: %s" %(request))

        #get qz answers
        #User must tick one checkbox and only one
        ansidlist = request.form.getlist("choices")

        # Just for testing setting userid = 1
        userid = 1

        #get all questions from Questions db
        query_obj = models.Anschoice.query.all()

        #Comparing quiz taker answers with actual ans choices in db
        for el in range(len(ansidlist)):
            for index in range(len(query_obj)):

                correct = 0
                if ((unicode(query_obj[index].ansid) == ansidlist[el]) and
                    (query_obj[index].correct == True)):
                        correct += 1

                if correct:
                    #get current quiz score from user table db
                    usrquery_obj = models.User.query.filter_by(userid=userid).all()
                    cur_qzscore= usrquery_obj[0].qzscore  
                    #increment quiz score and update user table in db
                    models.User.query.filter_by(userid=userid).\
                                  update(dict(qzscore=cur_qzscore+1))

        ans = models.Question.query.join(models.Anschoice).filter\
                         (models.Question.qzid == qzid).all()

        #put query_obj info in list format
        #questions[0].qid 
        #questions[0].ques_text
        #questions[0].ans[0].ansid
        #questions[0].ans[0].ans_choice
        #questions[0].ans[0].correct

        #get answers from quiz and put into placeholders in html

        utls.display_tables()

        # Return response
        response = make_response(render_template('answers.html', ans=ans, error=error), 200)
        return response


@app.route('/quizzes/<int:qzid>/<int:userid>/result', methods = ['GET', 'POST'])
def quiz_result(qzid, userid):

    # GET /user/quizzes/{qzid}/result
    if ((request.method == 'GET') or (request.method == 'POST')):
        error = None
        """Get result for taker of this  quiz"""
        logs.debug_ ("_________________________________________________")
        logs.debug_ ("UsrQuizRtAPI get fn: %s" %(request))

        # get user id for user - in this case just create default?
        userid = 1
        qzid = 1

        # Find quiz result for session
        query_obj = models.User.query.filter_by(userid=userid).first()
        score = query_obj.qzscore
        utls.display_tables()

        # Return response
        location = "/quizzes/%d/%d/result" % (qzid , userid)
        response = make_response(render_template('result.html', 
                                                 userid=userid,
                                                 qzid=qzid,
                                                 score=score,
                                                 error=error),
                                                 200)
        response.location=location
        return response

if __name__ == '__main__':

    #Initial config for db, this can be disabled
    models.db_init()

    utls.display_tables()
    app.debug = True

    app.run('192.168.33.10', 5001)

