from django.core.management import BaseCommand

from assignments.models import Assignment
import random
import json
from django.db.models import Q

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('jsonfile', type=str)

    def handle(self, *args, **options):
        jsonfile = options['jsonfile']
        self.stdout.write("Exporting assignments")
        assignment_list = []
        for assignment in Assignment.objects.filter(user_created=False):
            assignment_dict = {
                "title": assignment.title,
                "id": assignment.id,
                "text": assignment.assignment,
            }
            submissions = assignment.submissions.filter(text__isnull=False).filter(~Q(text=''))
            if submissions.count() > 0:
                example = random.choice(submissions)
                assignment_dict['example'] = example.text
            assignment_list.append(assignment_dict)

        with open(jsonfile, 'w') as f:
            f.write(json.dumps(assignment_list, indent=2, sort_keys=True))
