summaryrefslogtreecommitdiff
path: root/testapp/exam/views.py
blob: e2ff763017e675add434020e73c92a43dca5c23b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
import random
import string
import os
import stat
from os.path import dirname, pardir, abspath, join, exists
import datetime

from django.http import HttpResponse
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.http import Http404
from django.db.models import Sum
from taggit.models import Tag
from itertools import chain
# Local imports.
from exam.models import Quiz, Question, QuestionPaper
from exam.models import Profile, Answer, AnswerPaper, User
from exam.forms import UserRegisterForm, UserLoginForm, QuizForm, QuestionForm
from exam.xmlrpc_clients import code_server
from settings import URL_ROOT

# The directory where user data can be saved.
OUTPUT_DIR = abspath(join(dirname(__file__), pardir, 'output'))


def my_redirect(url):
    """An overridden redirect to deal with URL_ROOT-ing. See settings.py
    for details."""
    return redirect(URL_ROOT + url)


def my_render_to_response(template, context=None, **kwargs):
    """Overridden render_to_response.
    """
    if context is None:
        context = {'URL_ROOT': URL_ROOT}
    else:
        context['URL_ROOT'] = URL_ROOT
    return render_to_response(template, context, **kwargs)


def gen_key(no_of_chars):
    """Generate a random key of the number of characters."""
    allowed_chars = string.digits+string.uppercase
    return ''.join([random.choice(allowed_chars) for i in range(no_of_chars)])


def get_user_dir(user):
    """Return the output directory for the user."""

    user_dir = join(OUTPUT_DIR, str(user.username))
    if not exists(user_dir):
        os.mkdir(user_dir)
    # Make it rwx by others.
        os.chmod(user_dir, stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH\
                     | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR\
                     | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP)
    return user_dir


def is_moderator(user):
    """Check if the user is having moderator rights"""
    if user.groups.filter(name='moderator').count() == 1:
        return True


def fetch_questions(request):
    """Fetch questions from database based on the given search conditions &
    tags"""
    set1 = set()
    set2 = set()
    first_tag = request.POST.get('first_tag')
    first_condition = request.POST.get('first_condition')
    second_tag = request.POST.get('second_tag')
    second_condition = request.POST.get('second_condition')
    third_tag = request.POST.get('third_tag')
    question1 = set(Question.objects.filter(tags__name__in=[first_tag]))
    question2 = set(Question.objects.filter(tags__name__in=[second_tag]))
    question3 = set(Question.objects.filter(tags__name__in=[third_tag]))
    if first_condition == 'and':
        set1 = question1.intersection(question2)
        if second_condition == 'and':
            set2 = set1.intersection(question3)
        else:
            set2 = set1.union(question3)
    else:
        set1 = question1.union(question2)
        if second_condition == 'and':
            set2 = set1.intersection(question3)
        else:
            set2 = set1.union(question3)
    return set2


def index(request):
    """The start page.
    """
    user = request.user
    if user.is_authenticated():
        if user.groups.filter(name='moderator').count() > 0:
            return my_redirect('/exam/manage/')
        return my_redirect("/exam/start/")

    return my_redirect("/exam/login/")


def user_register(request):
    """ Register a new user.
    Create a user and corresponding profile and store roll_number also."""

    user = request.user
    if user.is_authenticated():
        return my_redirect("/exam/start/")

    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            u_name, pwd = form.save()
            new_user = authenticate(username=u_name, password=pwd)
            login(request, new_user)
            return my_redirect("/exam/start/")
        else:
            return my_render_to_response('exam/register.html',
                                         {'form': form},
                                         context_instance=RequestContext(request))
    else:
        form = UserRegisterForm()
        return my_render_to_response('exam/register.html',
                                     {'form': form}, context_instance=RequestContext(request))


def quizlist_user(request):
    """Show All Quizzes that is available to logged-in user."""
    user = request.user
    avail_quiz = list(QuestionPaper.objects.filter(quiz__active=True))
    user_answerpapers = AnswerPaper.objects.filter(user=user)
    user_quiz = []

    if user_answerpapers.count() == 0:
        context = {'quizzes': avail_quiz}
        return my_render_to_response("exam/quizzes_user.html", context)

    for paper in user_answerpapers:
        for quiz in avail_quiz:
            if paper.question_paper.id == quiz.id and \
                    paper.end_time != paper.start_time:
                avail_quiz.remove(quiz)

    context = {'quizzes': avail_quiz, 'user': user}
    return my_render_to_response("exam/quizzes_user.html", context)


def results_user(request):
    """Show list of Results of Quizzes that is taken by logged-in user."""
    user = request.user
    papers = AnswerPaper.objects.filter(user=user)
    quiz_marks = []
    for paper in papers:
        temp = paper.question_paper.quiz.description, paper.get_total_marks()
        quiz_marks.append(temp)
    context = {'papers': quiz_marks}
    return my_render_to_response("exam/results_user.html", context)


def edit_quiz(request):
    """Edit the list of quizzes seleted by the user for editing."""

    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    quiz_list = request.POST.getlist('quizzes')
    start_date = request.POST.getlist('start_date')
    duration = request.POST.getlist('duration')
    active = request.POST.getlist('active')
    description = request.POST.getlist('description')
    tags = request.POST.getlist('tags')

    for j, quiz_id in enumerate(quiz_list):
        quiz = Quiz.objects.get(id=quiz_id)
        quiz.start_date = start_date[j]
        quiz.duration = duration[j]
        quiz.active = active[j]
        quiz.description = description[j]
        quiz.save()
        edit_tags = tags[j]
        quiz.save()
        for tag in quiz.tags.all():
            quiz.tags.remove(tag)
        tags_split = edit_tags.split(', ')
        for i in range(0, len(tags_split)-1):
            tag = tags_split[i].strip()
            quiz.tags.add(tag)
    return my_redirect("/exam/manage/showquiz/")


def edit_question(request):
    """Edit the list of questions seleted by the user for editing."""
    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    question_list = request.POST.getlist('questions')
    summary = request.POST.getlist('summary')
    description = request.POST.getlist('description')
    points = request.POST.getlist('points')
    test = request.POST.getlist('test')
    options = request.POST.getlist('options')
    type = request.POST.getlist('type')
    active = request.POST.getlist('active')
    snippet = request.POST.getlist('snippet')
    tags = request.POST.getlist('tags')
    for j, question_id in enumerate(question_list):
        question = Question.objects.get(id=question_id)
        question.summary = summary[j]
        question.description = description[j]
        question.points = points[j]
        question.test = test[j]
        question.options = options[j]
        question.active = active[j]
        question.snippet = snippet[j]
        question.type = type[j]
        edit_tags = tags[j]
        question.save()
        for tag in question.tags.all():
            question.tags.remove(tag)
        tags_split = edit_tags.split(',')
        for i in range(0, len(tags_split)-1):
            tag = tags_split[i].strip()
            question.tags.add(tag)
    return my_redirect("/exam/manage/questions")


def add_question(request, question_id=None):
    """To add a new question in the database.
    Create a new question and store it."""
    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            if question_id is None:
                form.save()
                question = Question.objects.order_by("-id")[0]
                tags = form['tags'].data.split(',')
                for i in range(0, len(tags)-1):
                    tag = tags[i].strip()
                    question.tags.add(tag)
                return my_redirect("/exam/manage/questions")
            else:
                d = Question.objects.get(id=question_id)
                d.summary = form['summary'].data
                d.description = form['description'].data
                d.points = form['points'].data
                d.test = form['test'].data
                d.options = form['options'].data
                d.type = form['type'].data
                d.active = form['active'].data
                d.snippet = form['snippet'].data
                d.save()
                question = Question.objects.get(id=question_id)
                for tag in question.tags.all():
                    question.tags.remove(tag)
                tags = form['tags'].data.split(',')
                for i in range(0, len(tags)-1):
                    tag = tags[i].strip()
                    question.tags.add(tag)
                return my_redirect("/exam/manage/questions")
        else:
            return my_render_to_response('exam/add_question.html',
                                         {'form': form}, context_instance=RequestContext(request))
    else:
        if question_id is None:
            form = QuestionForm()
            return my_render_to_response('exam/add_question.html',
                                         {'form': form}, context_instance=RequestContext(request))
        else:
            d = Question.objects.get(id=question_id)
            form = QuestionForm()
            form.initial['summary'] = d.summary
            form.initial['description'] = d.description
            form.initial['points'] = d.points
            form.initial['test'] = d.test
            form.initial['options'] = d.options
            form.initial['type'] = d.type
            form.initial['active'] = d.active
            form.initial['snippet'] = d.snippet
            form_tags = d.tags.all()
            form_tags_split = form_tags.values('name')
            initial_tags = ""
            for tag in form_tags_split:
                initial_tags = initial_tags + str(tag['name']).strip() + ","
            if (initial_tags == ","):
                initial_tags = ""
            form.initial['tags'] = initial_tags
            return my_render_to_response('exam/add_question.html',
                                         {'form': form},
                                         context_instance=RequestContext(request))


def add_quiz(request, quiz_id=None):
    """To add a new quiz in the database.
    Create a new quiz and store it."""

    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    if request.method == "POST":
        form = QuizForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            if quiz_id is None:
                form.save()
                quiz = Quiz.objects.order_by("-id")[0]
                tags = form['tags'].data.split(',')
                for tag in tags:
                    tag = tag.strip()
                    quiz.tags.add(tag)
                return my_redirect("/exam/manage/designquestionpaper")
            else:
                d = Quiz.objects.get(id=quiz_id)
                d.start_date = form['start_date'].data
                d.duration = form['duration'].data
                d.active = form['active'].data
                d.description = form['description'].data
                d.save()
                quiz = Quiz.objects.get(id=quiz_id)
                for tag in quiz.tags.all():
                    quiz.tags.remove(tag)
                tags = form['tags'].data.split(',')
                for i in range(0, len(tags)-1):
                    tag = tags[i].strip()
                    quiz.tags.add(tag)
                return my_redirect("/exam/manage/showquiz")
        else:
            return my_render_to_response('exam/add_quiz.html',
                                         {'form': form},
                                         context_instance=RequestContext(request))
    else:
        if quiz_id is None:
            form = QuizForm()
            return my_render_to_response('exam/add_quiz.html',
                                         {'form': form},
                                         context_instance=RequestContext(request))
        else:
            d = Quiz.objects.get(id=quiz_id)
            form = QuizForm()
            form.initial['start_date'] = d.start_date
            form.initial['duration'] = d.duration
            form.initial['description'] = d.description
            form.initial['active'] = d.active
            form_tags = d.tags.all()
            form_tags_split = form_tags.values('name')
            initial_tags = ""
            for tag in form_tags_split:
                initial_tags = initial_tags + str(tag['name']).strip() + ","
            if (initial_tags == ","):
                initial_tags = ""
            form.initial['tags'] = initial_tags
            return my_render_to_response('exam/add_quiz.html',
                                         {'form': form},
                                         context_instance=RequestContext(request))


def design_questionpaper(request, questionpaper_id=None):
    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    return my_render_to_response('exam/add_questionpaper.html', {},
                                 context_instance=RequestContext(request))


def show_all_questionpapers(request, questionpaper_id=None):
    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    if request.method == "POST" and request.POST.get('add') == "add":
        return my_redirect("/exam/manage/designquestionpaper/" + \
                               questionpaper_id)

    if request.method == "POST" and request.POST.get('delete') == "delete":
        data = request.POST.getlist('papers')
        q_paper = QuestionPaper.objects.get(id=questionpaper_id)
        for i in data:
            q_paper.questions.remove(Question.objects.get(id=i))
        question_paper = QuestionPaper.objects.all()
        context = {'papers': question_paper}
        return my_render_to_response('exam/showquestionpapers.html', context,
                                     context_instance=RequestContext(request))
    if questionpaper_id is None:
        qu_papers = QuestionPaper.objects.all()
        context = {'papers': qu_papers}
        return my_render_to_response('exam/showquestionpapers.html', context,
                                     context_instance=RequestContext(request))
    else:
        qu_papers = QuestionPaper.objects.get(id=questionpaper_id)
        quiz = qu_papers.quiz
        questions = qu_papers.questions.all()
        context = {'papers': {'quiz': quiz, 'questions': questions}}
        return my_render_to_response('exam/editquestionpaper.html', context,
                                     context_instance=RequestContext(request))


def automatic_questionpaper(request, questionpaper_id=None):
    """Generate automatic question paper for a particular quiz"""

    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    if questionpaper_id is None:
        if request.method == "POST":
            if request.POST.get('save') == 'save':
                quiz = Quiz.objects.order_by("-id")[0]
                quest_paper = QuestionPaper()
                questions = request.POST.getlist('questions')
                tot_marks = 0
                for quest in questions:
                    if quest.isdigit():
                        q = Question.objects.get(id=quest)
                        tot_marks += q.points
                quest_paper.quiz = quiz
                quest_paper.total_marks = tot_marks
                quest_paper.save()
                for quest in questions:
                    if quest.isdigit():
                        q = Question.objects.get(id=quest)
                        quest_paper.questions.add(q)
                return my_redirect('/exam/manage/showquiz')
            else:
                no_questions = int(request.POST.get('questions'))
                fetched_questions = fetch_questions(request)
                n = len(fetched_questions)
                msg = ''
                if (no_questions < n):
                    i = n - no_questions
                    for i in range(0, i):
                        fetched_questions.pop()
                elif (no_questions > n):
                    msg = 'The given Criteria does not satisfy the number\
                    of Questions...'
                tags = Tag.objects.all()
                context = {'data': {'questions': fetched_questions,
                                    'tags': tags,
                                    'msg': msg}}
                return my_render_to_response(\
                    'exam/automatic_questionpaper.html', context,
                    context_instance=RequestContext(request))
        else:
            tags = Tag.objects.all()
            context = {'data': {'tags': tags}}
            return my_render_to_response('exam/automatic_questionpaper.html',
                                         context, context_instance=RequestContext(request))

    else:
        if request.method == "POST":
            if request.POST.get('save') == 'save':
                quest_paper = QuestionPaper.objects.get(id=questionpaper_id)
                questions = request.POST.getlist('questions')
                tot_marks = quest_paper.total_marks
                for quest in questions:
                    if quest.isdigit():
                        q = Question.objects.get(id=quest)
                        tot_marks += q.points
                quest_paper.total_marks = tot_marks
                quest_paper.save()
                for quest in questions:
                    if quest.isdigit():
                        q = Question.objects.get(id=quest)
                        quest_paper.questions.add(q)
                return my_redirect('/exam/manage/showquiz')
            else:
                no_questions = int(request.POST.get('questions'))
                fetched_questions = fetch_questions(request)
                n = len(fetched_questions)
                msg = ''
                if(no_questions < n):
                    i = n - no_questions
                    for i in range(0, i):
                        fetched_questions.pop()
                elif(no_questions > n):
                    msg = 'The given Criteria does not satisfy the number of \
                                                                Questions...'
                tags = Tag.objects.all()
                context = {'data': {'questions': fetched_questions,
                                    'tags': tags,
                                    'msg': msg}}
                return my_render_to_response\
                    ('exam/automatic_questionpaper.html', context,
                     context_instance=RequestContext(request))
        else:
            tags = Tag.objects.all()
            context = {'data': {'tags': tags}}
            return my_render_to_response('exam/automatic_questionpaper.html',
                                         context, context_instance=RequestContext(request))


def manual_questionpaper(request, questionpaper_id=None):
    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    if questionpaper_id is None:
        if request.method == "POST":
            if request.POST.get('save') == 'save':
                questions = request.POST.getlist('questions')
                quest_paper = QuestionPaper()
                quiz = Quiz.objects.order_by("-id")[0]
                tot_marks = 0
                for quest in questions:
                    if quest.isdigit():
                        q = Question.objects.get(id=quest)
                        tot_marks += q.points
                quest_paper.quiz = quiz
                quest_paper.total_marks = tot_marks
                quest_paper.save()
                for i in questions:
                    q = Question.objects.get(id=i)
                    quest_paper.questions.add(q)
                return my_redirect('/exam/manage/showquiz')
            else:
                fetched_questions = fetch_questions(request)
                n = len(fetched_questions)
                msg = ''
                if (n == 0):
                    msg = 'No matching Question found...'
                tags = Tag.objects.all()
                context = {'data': {'questions': fetched_questions,\
                                        'tags': tags, 'msg': msg}}
                return my_render_to_response('exam/manual_questionpaper.html',
                                             context,
                                             context_instance=RequestContext(request))
        else:
            tags = Tag.objects.all()
            context = {'data': {'tags': tags}}
            return my_render_to_response('exam/manual_questionpaper.html',
                                         context, context_instance=RequestContext(request))

    else:
        if request.method == "POST":
            if request.POST.get('save') == 'save':
                quest_paper = QuestionPaper.objects.get(id=questionpaper_id)
                questions = request.POST.getlist('questions')
                tot_marks = quest_paper.total_marks
                for quest in questions:
                    q = Question.objects.get(id=quest)
                    tot_marks += q.points
                    quest_paper.total_marks = tot_marks
                    quest_paper.save()
                    for i in questions:
                        q = Question.objects.get(id=i)
                        quest_paper.questions.add(q)
                        return my_redirect('/exam/manage/showquiz')
            else:
                fetched_questions = fetch_questions(request)
                n = len(fetched_questions)
                msg = ''
                if (n == 0):
                    msg = 'No matching Question found...'
                tags = Tag.objects.all()
                context = {'data': {'questions': fetched_questions,\
                                        'tags': tags, 'msg': msg}}
                return my_render_to_response('exam/manual_questionpaper.html',
                                             context,
                                             context_instance=RequestContext(request))
        else:
            tags = Tag.objects.all()
            context = {'data': {'tags': tags}}
            return my_render_to_response('exam/manual_questionpaper.html',
                                         context, context_instance=RequestContext(request))



def prof_manage(request):
    """Take credentials of the user with professor/moderator
    rights/permissions and log in."""
    user = request.user
    if user.is_authenticated()\
            and user.groups.filter(name='moderator').count() > 0:
        context = {'user': user}
        return my_render_to_response('manage.html', context)
    return my_redirect('/exam/login/')


def user_login(request):
    """Take the credentials of the user and log the user in."""

    user = request.user
    if user.is_authenticated():
        if user.groups.filter(name='moderator').count() > 0:
            return my_redirect('/exam/manage/')
        return my_redirect("/exam/intro/")

    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data
            login(request, user)
            if user.groups.filter(name='moderator').count() > 0:
                return my_redirect('/exam/manage/')
            return my_redirect('/exam/login/')
        else:
            context = {"form": form}
            return my_render_to_response('exam/login.html', context,
                                         context_instance=RequestContext(request))
    else:
        form = UserLoginForm()
        context = {"form": form}
        return my_render_to_response('exam/login.html', context,
                                     context_instance=RequestContext(request))


def start(request, questionpaper_id=None):
    """Check the user cedentials and if any quiz is available,
    start the exam."""
    user = request.user
    if questionpaper_id is None:
        return my_redirect('/exam/quizzes/')
    try:
        """Right now the app is designed so there is only one active quiz
        at a particular time."""
        questionpaper = QuestionPaper.objects.get(id=questionpaper_id)
    except QuestionPaper.DoesNotExist:
        msg = 'Quiz not found, please contact your '\
            'instructor/administrator. Please login again thereafter.'
        return complete(request, reason=msg)

    try:
        old_paper = AnswerPaper.objects.get(\
            question_paper=questionpaper, user=user)
        q = old_paper.current_question()
        return show_question(request, q, questionpaper_id)
    except AnswerPaper.DoesNotExist:
        ip = request.META['REMOTE_ADDR']
        key = gen_key(10)
        try:
            profile = user.get_profile()
        except Profile.DoesNotExist:
            msg = 'You do not have a profile and cannot take the quiz!'
            raise Http404(msg)

        new_paper = AnswerPaper(user=user, user_ip=ip,
                                question_paper=questionpaper, profile=profile)
        new_paper.start_time = datetime.datetime.now()
        new_paper.end_time = datetime.datetime.now()
        # Make user directory.
        user_dir = get_user_dir(user)

        questions = [str(_.id) for _ in questionpaper.questions.all()]
        random.shuffle(questions)

        #questions = questionpaper.questions
        #random.shuffle(questions)
        new_paper.questions = "|".join(questions)
        new_paper.save()
        # Show the user the intro page.
        context = {'user': user, 'paper_id': questionpaper_id}
        ci = RequestContext(request)
        return my_render_to_response('exam/intro.html', context,
                                     context_instance=ci)


def question(request, q_id, questionpaper_id,success_msg=None):
    """Check the credentials of the user and start the exam."""

    user = request.user
    if not user.is_authenticated():
        return my_redirect('/exam/login/')
    q = get_object_or_404(Question, pk=q_id)
    try:
        q_paper = QuestionPaper.objects.get(id=questionpaper_id)
        paper = AnswerPaper.objects.get(\
            user=request.user, question_paper=q_paper)
    except AnswerPaper.DoesNotExist:
        return my_redirect('/exam/start/')
    if not paper.question_paper.quiz.active:
        return complete(request, reason='The quiz has been deactivated!')

    time_left = paper.time_left()
    if time_left == 0:
        return complete(request, reason='Your time is up!')
    quiz_name = paper.question_paper.quiz.description
    if success_msg is None:
        context = {'question': q, 'paper': paper, 'user': user,
                   'quiz_name': quiz_name,
                   'time_left': time_left,}
    
    else:
        context = {'question': q, 'paper': paper, 'user': user,
                   'quiz_name': quiz_name,
                   'time_left': time_left,
                   'success_msg':success_msg}
    
    ci = RequestContext(request)
    return my_render_to_response('exam/question.html', context, 
                                 context_instance=ci)


def show_question(request, q_id, questionpaper_id,success_msg=None,
                  answerpaper_id=None):
    """Show a question if possible."""
    if len(q_id) == 0:
        msg = 'Congratulations!  You have successfully completed the quiz.'
        return complete(request, msg,answerpaper_id)
    else:
        return question(request, q_id, questionpaper_id,success_msg)


def check(request, q_id, questionpaper_id=None):
    """Checks the answers of the user for particular question"""    

    user = request.user
    if not user.is_authenticated():
        return my_redirect('/exam/login/')
    question = get_object_or_404(Question, pk=q_id)
    q_paper = QuestionPaper.objects.get(id=questionpaper_id)
    paper = AnswerPaper.objects.get(user=request.user, question_paper=q_paper)
    snippet_code = request.POST.get('snippet')
    user_answer = request.POST.get('answer')
    skip = request.POST.get('skip', None)
    if skip is not None:
        next_q = paper.skip()
        return show_question(request, next_q, questionpaper_id)
    
    if question.type == 'mcq':
        # Add the answer submitted, regardless of it being correct or not.
        new_answer = Answer(question=question, answer=user_answer,
                            correct=False)
        new_answer.save()
        paper.answers.add(new_answer)
    else:
        """Add the answer submitted with the Snippet code,
        regardless of it being correct or not."""
        answer_check = snippet_code + "\n" + user_answer
        new_answer = Answer(question=question, answer=answer_check,
                            correct=False)
        new_answer.save()
        paper.answers.add(new_answer)

    # If we were not skipped, we were asked to check.  For any non-mcq
    # questions, we obtain the results via XML-RPC with the code executed
    # safely in a separate process (the code_server.py) running as nobody.
    if question.type == 'mcq':
        success = True  # Only one attempt allowed for MCQ's.
        if user_answer.strip() == question.test.strip():
            new_answer.correct = True
            new_answer.marks = question.points
            new_answer.error = 'Correct answer'
        else:
            new_answer.error = 'Incorrect answer'
    else:
        user_dir = get_user_dir(user)
        success, err_msg = code_server.run_code(answer_check, question.test, 
                                                user_dir, question.type)
        new_answer.error = err_msg
        if success:
            # Note the success and save it along with the marks.
            new_answer.correct = success
            new_answer.marks = question.points

    new_answer.save()

    if not success:  # Should only happen for non-mcq questions.
        time_left = paper.time_left()
        if time_left == 0:
            return complete(request, reason='Your time is up!')
        if not paper.question_paper.quiz.active:
            return complete(request, reason='The quiz has been deactivated!')
        context = {'question': question, 'error_message': err_msg,
                   'paper': paper, 'last_attempt': user_answer,
                   'quiz_name': paper.question_paper.quiz.description,
                   'time_left': time_left}
        ci = RequestContext(request)

        return my_render_to_response('exam/question.html', context, 
                                     context_instance=ci)
    else:
        next_q = paper.completed_question(question.id)
        success_msg = True
        return show_question(request, next_q, questionpaper_id,success_msg,
                             paper.id)


def quit(request, answerpaper_id=None):
    """Show the quit page when the user logs out."""
    context = {'id': answerpaper_id}
    return my_render_to_response('exam/quit.html', context,
                                 context_instance=RequestContext(request)) 


def complete(request, reason=None, answerpaper_id=None):
    """Show a page to inform user that the quiz has been compeleted."""
    
    user = request.user
    if answerpaper_id is None:
        logout(request)
        context = {'message': "You are successfully Logged out."}
        return my_render_to_response('exam/complete.html', context)
    else:
        paper = AnswerPaper.objects.get(id=answerpaper_id)
        obt_marks = paper.get_total_marks()
        tot_marks = paper.question_paper.total_marks
        print tot_marks
        if obt_marks == paper.question_paper.total_marks:
            context = {'message': "Hurray ! You did an excellent job.\
			you answered all the questions correctly.\
			You have been logged out successfully,\
			Thank You !"}
            logout(request)
            return my_render_to_response('exam/complete.html',context)
        else:
            context = {'message': reason}
            logout(request)
            return my_render_to_response('exam/complete.html',context)
    no = False
    message = reason or 'The quiz has been completed. Thank you.'
    if user.groups.filter(name='moderator').count() > 0:
        message = 'You are successfully Logged out.'
    if request.method == 'POST' and 'no' in request.POST:
        no = True
    if not no:
        # Logout the user and quit with the message given.
        answer_paper = AnswerPaper.objects.get(id=answerpaper_id)
        answer_paper.endtime = datetime.datetime.now()
        answer_paper.save()
        return my_redirect('/exam/quizzes/')
    else:
        return my_redirect('/exam/')


def monitor(request, quiz_id=None):
    """Monitor the progress of the papers taken so far."""

    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    if quiz_id is None:
        q_paper = QuestionPaper.objects.all()
        context = {'papers': [], 
                   'quiz': None, 
                   'quizzes': q_paper}
        return my_render_to_response('exam/monitor.html', context,
                                     context_instance=RequestContext(request)) 
    # quiz_id is not None.
    try:
        quiz = QuestionPaper.objects.get(id=quiz_id)
    except QuestionPaper.DoesNotExist:
        papers = []
        quiz = None
    else:
        papers = AnswerPaper.objects.all().annotate(
            total=Sum('answers__marks')).order_by('-total')

    context = {'papers': papers, 'quiz': quiz, 'quizzes': None}
    return my_render_to_response('exam/monitor.html', context,
                                 context_instance=RequestContext(request)) 


def get_user_data(username):
    """For a given username, this returns a dictionary of important data
    related to the user including all the user's answers submitted.
    """
    user = User.objects.get(username=username)
    papers = AnswerPaper.objects.filter(user=user)

    data = {}
    try:
        profile = user.get_profile()
    except Profile.DoesNotExist:
        # Admin user may have a paper by accident but no profile.
        profile = None
    data['user'] = user
    data['profile'] = profile
    data['papers'] = papers 
    return data


def show_all_users(request):
    """Shows all the users who have taken various exams/quiz."""

    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page !')
    user = User.objects.filter(username__contains="")
    questionpaper = AnswerPaper.objects.all()
    context = {'question': questionpaper}
    return my_render_to_response('exam/showusers.html', context,
                                 context_instance=RequestContext(request))


def show_all_quiz(request):
    """Generates a list of all the quizzes
    that are currently in the database."""

    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page !')

    if request.method == 'POST' and request.POST.get('delete') == 'delete':
        data = request.POST.getlist('quiz')

        if data is None:
            quizzes = Quiz.objects.all()
            context = {'papers': [], 
                       'quiz': None, 
                       'quizzes': quizzes}
            return my_render_to_response('exam/show_quiz.html', context,
                                         context_instance=RequestContext(request))  
        else:
            for i in data:
                quiz = Quiz.objects.get(id=i).delete()
            quizzes = Quiz.objects.all()
            context = {'papers': [], 
                       'quiz': None, 
                       'quizzes': quizzes}
            return my_render_to_response('exam/show_quiz.html', context,
                                         context_instance=RequestContext(request))

    elif request.method == 'POST' and request.POST.get('edit') == 'edit':
        data = request.POST.getlist('quiz')
        forms = []
        for j in data:
            d = Quiz.objects.get(id=j)
            form = QuizForm()
            form.initial['start_date'] = d.start_date
            form.initial['duration'] = d.duration
            form.initial['active'] = d.active
            form.initial['description'] = d.description
            form_tags = d.tags.all()
            form_tags_split = form_tags.values('name')
            initial_tags = ""
            for tag in form_tags_split:
                initial_tags = initial_tags + str(tag['name']).strip() + ","
            if (initial_tags == ","):
                initial_tags = ""
            form.initial['tags'] = initial_tags
            forms.append(form)
        return my_render_to_response('exam/edit_quiz.html',
                                     {'forms': forms, 'data': data},
                                     context_instance=RequestContext(request))
    else:
        quizzes = Quiz.objects.all()
        context = {'papers': [], 
                   'quiz': None, 
                   'quizzes': quizzes}
        return my_render_to_response('exam/show_quiz.html', context,
                                     context_instance=RequestContext(request)) 


def show_all_questions(request):
    """Show a list of all the questions currently in the databse."""

    user = request.user
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404("You are not allowed to view this page !")

    if request.method == 'POST' and request.POST.get('delete') == 'delete':
        data = request.POST.getlist('question')
        if data is None:
            questions = Question.objects.all()
            context = {'papers': [],
                       'question': None,
                       'questions': questions}
            return my_render_to_response('exam/showquestions.html', context,
                                         context_instance=RequestContext(request))  
        else:
            for i in data:
                question = Question.objects.get(id=i).delete()
            questions = Question.objects.all()
            context = {'papers': [],
                       'question': None,
                       'questions': questions}
            return my_render_to_response('exam/showquestions.html', context,
                                         context_instance=RequestContext(request))
    elif request.method == 'POST' and request.POST.get('edit') == 'edit':
        data = request.POST.getlist('question')

        forms = []
        for j in data:
            d = Question.objects.get(id=j)
            form = QuestionForm()
            form.initial['summary'] = d.summary
            form.initial['description'] = d.description
            form.initial['points'] = d.points
            form.initial['test'] = d.test
            form.initial['options'] = d.options
            form.initial['type'] = d.type
            form.initial['active'] = d.active
            form_tags = d.tags.all()
            form_tags_split = form_tags.values('name')
            initial_tags = ""
            for tag in form_tags_split:
                initial_tags = initial_tags + str(tag['name']).strip() + ","
            if (initial_tags == ","):
                initial_tags = ""
            form.initial['tags'] = initial_tags
            forms.append(form)
        return my_render_to_response('exam/edit_question.html',
                                     {'forms': forms, 'data': data},
                                     context_instance=RequestContext(request))
    else:
        questions = Question.objects.all()
        context = {'papers': [],
                   'question': None,
                   'questions': questions}
        return my_render_to_response('exam/showquestions.html', context,
                                     context_instance=RequestContext(request))


def user_data(request, username):
    """Render user data."""

    current_user = request.user
    if not current_user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    data = get_user_data(username)

    context = {'data': data}
    return my_render_to_response('exam/user_data.html', context,
                                 context_instance=RequestContext(request))


def grade_user(request, username):
    """Present an interface with which we can easily grade a user's papers
    and update all their marks and also give comments for each paper.
    """
    current_user = request.user
    if not current_user.is_authenticated() or not is_moderator(current_user):
        raise Http404('You are not allowed to view this page!')

    data = get_user_data(username)
    if request.method == 'POST':
        papers = data['papers']
        for paper in papers:
            for question, answers in paper.get_question_answers().iteritems():
                marks = float(request.POST.get('q%d_marks' % question.id))
                last_ans = answers[-1]
                last_ans.marks = marks
                last_ans.save()
            paper.comments = request.POST.get(\
                'comments_%d' % paper.question_paper.id)
            paper.save()

        context = {'data': data}
        return my_render_to_response('exam/user_data.html', context,
                                     context_instance=RequestContext(request))
    else:
        context = {'data': data}
        return my_render_to_response('exam/grade_user.html', context,
                                     context_instance=RequestContext(request))