#!/usr/bin/env python3

"""
Python dbwebb module for asserting and auto correcting labs.

It reads the answers from a json-file and use it
for checking with assert_equal().
"""

import json
import sys


class Dbwebb():
    """
    Class for autocorrecting labs.
    """

    # Texts
    no_answer = "Replace this text with the variable holding the answer."
    text_no_answer = "{prompt} {question} NOT YET DONE."
    text_correct = """{prompt} {question} CORRECT. Well done!
{answer}"""
    text_fail = """{prompt} {question} FAIL.
{prompt} You said:
{answer} {type}
{prompt}"""
    text_hint = """Hint:
{answer} {type}"""

    # pylint: disable=line-too-long
    text_done = """{prompt} Done with status {total}/{correct}/{failed}/{not_done} (Total/Correct/Failed/Not done)."""  # noqa
    # pylint: enable=line-too-long

    text_pass = "\033[92m{prompt}Grade: PASS! :-)\033[0m"
    text_no_pass = "\033[93m{prompt}Grade: Thou Did Not Pass. :-|\033[0m"

    def __init__(self, answersFileName="answer.json"):
        """
        Init by reading json-file with answers.
        """
        self.answers = json.load(open(answersFileName))
        self.correct = 0
        self.failed = 0
        self.not_done = 0
        self.prompt = ">>> "

    def assert_equal(self, question, answer, hint=False):
        """
        Check if the answer is correct or not, present a hint if asked for.
        """
        status = None

        if answer == self.no_answer:
            status = self.text_no_answer.format(self.prompt, question)
            self.not_done += 1

        elif answer == self.answers["answers"][question]:
            status = self.text_correct.format(
                self.prompt,
                question,
                json.dumps(answer)
            )
            self.correct += 1

        else:
            status = self.text_fail.format(
                prompt=self.prompt,
                question=question,
                answer=json.dumps(answer),
                type=str(type(answer))
            )

            if hint:
                status += self.text_hint.format(
                    answer=self.answers["answers"][question],
                    type=str(type(self.answers["answers"][question]))
                )

            self.failed += 1

        return status

    def exit_with_summary(self):
        """
        Print a exit message with the result of all tests.
        Exit with status 0 if all tasks are solved, else exit with status 1.
        """
        total = len(self.answers["answers"])
        print(self.text_done.format(
            self.prompt,
            total,
            self.correct,
            self.failed,
            self.not_done
        ))

        # Grading
        if total == self.correct:
            print(self.text_pass.format(self.prompt))
            sys.exit(0)
        else:
            print(self.text_no_pass.format(self.prompt))
            sys.exit(42)
