from xml.dom.minidom import parse, Node

from django.core.management.base import NoArgsCommand

from offline.quiz.models import QuestionBank, Quiz

name2num = {"day1quiz1" : "11",
            "day1quiz2" : "12",
            "day2quiz1" : "21",
           }

def seed_que():
    for question in QuestionBank.objects.all():
        question.delete()

    q_bank = parse("question_bank.xml").getElementsByTagName("question")
    for question in q_bank:
        quiz_name = question.parentNode.tagName
        quiz_num = name2num[quiz_name]

        description_node = question.getElementsByTagName("description")[0]
        description = (description_node.childNodes[0].data).strip()

        time_limit_node = question.getElementsByTagName("time_limit")[0]
        time_limit = time_limit_node.childNodes[0].data


        options_nodes = question.getElementsByTagName("options")
        options = (options_nodes[0].childNodes[0].data).strip() if options_nodes else ""

        code_nodes = question.getElementsByTagName("code")
        code = (code_nodes[0].childNodes[0].data).strip() if code_nodes else ""

        expected_ans_node = question.getElementsByTagName("expected_answer")[0]
        expected_ans = (expected_ans_node.childNodes[0].data).strip()

        new_question = QuestionBank(quiz_num = quiz_num, 
                                    description = description, 
                                    time_limit = time_limit,
                                    options = options,
                                    code = code,
                                    expected_ans = expected_ans,
                                   )
        new_question.save()
    
class Command(NoArgsCommand):
    
    def handle_noargs(self, **options):
        """ Just copied the code from seed_db.py """
        
        seed_que()
