from .models import Entry
from .tools.data import load
from .tools.quiz import compile_results, evaluate_answers, render_questions

from flask import Blueprint, jsonify, request

import numpy

views = Blueprint(
    name='views',
    import_name=__name__
)

@views.route('/questions/')
def _questions():    
    return render_questions()

@views.route('/submit/', methods=['POST'])
def _submit():
    answers = request.json
    scores = evaluate_answers(answers)
    results = compile_results(results=scores)
    new_entry = Entry(answers=answers, results=results)
    new_entry.add()
    return jsonify(results)

@views.route('/count/')
def _count():
    return jsonify(len(Entry.query.all()))

@views.route('/playbooks/')
def _playbooks():
    playbooks = dict.fromkeys(load('playbooks.json'), 0)
    for entry in Entry.query.all():
        for _playbook in entry.results['playbooks']: playbooks[_playbook] += 1
    return playbooks

@views.route('/answers/')
def _answers():
    answers = { }
    for index, question in enumerate(render_questions()):
        answers[index] = { }
        for _index, answer in enumerate(question['answers']): answers[index][_index] = 0
    for entry in Entry.query.all():
        for index, answer in enumerate(entry.answers):
            if type(answer) is list:
                for option in answer: answers[index][option] += 1
            else:
                answers[index][answer] += 1
    return list(answers.values())

@views.route('/scores/')
def _scores():
    playbooks = { playbook: list() for playbook in load('playbooks.json') }
    for playbook, scores in playbooks.items():
        for entry in Entry.query.all():
            score = entry.results['all_playbooks'][playbook]
            percentage_score = 100 * score/entry.results['max_score']
            scores.append(percentage_score)
    output = { playbook: dict() for playbook in playbooks }
    for playbook, scores in playbooks.items():
        output[playbook]['mean'] = numpy.mean(scores)
        output[playbook]['median'] = numpy.median(scores)
        output[playbook]['standard_deviation'] = numpy.std(scores)
    return output