#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Standardized types do not require authors to specify any control script as
# it can be generated on import. However when provided it will overwrite the
# default behaivior.

import sys
import re


def grade(ctx):
    grade = 'FAIL'

    # counter
    correct = 0
    correct_chosen = []
    min_correct = -1

    incorrect = 0
    incorrect_chosen = []
    max_incorrect = 0

    choices = ctx.data['data']['choices']
    solution = ctx.data['solution']

    print(choices, file=sys.stderr)
    print(solution, file=sys.stderr)

    if ctx.data['data']['input_type'] in ['radio']:
        # choose one
        # a correct selection is found? => return 'PASS'
        # a incorrect selection is found? => return 'FAIL'
        for choice in choices:
            print(choice['value'], file=sys.stderr)
            print(solution, file=sys.stderr)

            if choice['is'] in ['correct', 'required']:
                if choice['value'] in solution:
                    correct_chosen.append(choice['value'])
                    grade = 'PASS'
                    break
            else:
                if choice['value'] in solution:
                    incorrect_chosen.append(choice['value'])
                    grade = 'FAIL'
                    break
    else:
        # choose many/multiple
        #for choice in  ctx.data['choices']:
        for choice in choices:
            print(choice['value'], file=sys.stderr)
            print(solution, file=sys.stderr)

            if choice['is'] in ['correct', 'required']:
                correct += 1
                if choice['value'] in solution:
                    correct_chosen.append(choice['value'])
            else:
                incorrect += 1
                if choice['value'] in solution:
                    incorrect_chosen.append(choice['value'])

        if min_correct == -1:
            min_correct = correct

        print({
            'correct': correct,
            'correct_chosen': correct_chosen,
            'min_correct': min_correct,
            'incorrect': incorrect,
            'incorrect_chosen': incorrect_chosen,
            'max_incorrect': max_incorrect,
            }, file=sys.stderr)

        ctx.response_data['correct'] = correct_chosen
        ctx.response_data['incorrect'] = incorrect_chosen

        if len(incorrect_chosen) > max_incorrect:
            return 'FAIL'

        elif len(correct_chosen) < min_correct:
            return 'FAIL'
        
        if len(correct_chosen) == correct:
            return 'PASS'

    # grading
    # max_incorrect
    # min_correct

    ctx.response_data['correct'] = correct_chosen
    ctx.response_data['incorrect'] = incorrect_chosen

    return grade
