from flask import Flask, url_for, request, render_template;
from app import appVar;
import redis;

# Plug in to NoSQL Redis DB Server
r = redis.StrictRedis(host='localhost', port=6379, db=0, charset='utf-8', decode_responses=True)

#main_page
@appVar.route('/')
def hello():        
    myLink = url_for('fCreate')
    qList = r.keys('*:q')
    return render_template('TriviaIndex.html', questions=qList, Link=myLink)

#sub_page
@appVar.route('/createPage', methods=['GET', 'POST'])
def fCreate():
    if request.method == 'GET':
        # return empty form
        return render_template('CreateQuestion.html')

    elif request.method == 'POST':
        # reqad form data
        titleV = request.form['title']
        answerV = request.form['answer']
        questionV = request.form['question']
        
        # save data to db
        r.set(titleV+':q', questionV)
        r.set(titleV+':a', answerV)

        return render_template('SubmitedPage.html', question = questionV)

    else:
        return "<h2>Invalid request</h2>"

#var_page
@appVar.route('/q/<tVar>', methods=['GET', 'POST'])
def fQest(tVar):
    if request.method == 'GET':
        # Prepeare and read from

        #get question from db
        dbQuestion = r.get(tVar+':q')        
        return render_template('AnswerQuestion.html', question = dbQuestion)

    elif request.method == 'POST': 
        # checking answer
        userAnswer = request.form['answer']
        dbAnswer = r.get(tVar+':a')

        if userAnswer == dbAnswer:
            return render_template('QCorrectPage.html')
        else:
            return render_template('QWrongPage.html', rAnswer=dbAnswer, uAnswer=userAnswer)


    return "<h2>" + tVar + "</h2>"