# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-10-19 10:38
from __future__ import unicode_literals

from django.db import migrations
from django.core.urlresolvers import reverse

def create_explanation_revisions(apps, schema_editor):
    Question = apps.get_model('exams', 'Question')
    Revision = apps.get_model('exams', 'Revision')
    Highlight = apps.get_model('exams', 'Highlight')
    Answer = apps.get_model('exams', 'Answer')
    ExplanationRevision = apps.get_model('exams', 'ExplanationRevision')

    for revision in Revision.objects.select_related('submitter',
                                                    'question')\
                                    .filter(is_deleted=False,
                                            question__is_deleted=False)\
                                    .exclude(explanation="",
                                             explanation_figure="",
                                             reference="")\
                                    .order_by('pk'):

        # If the only thing that has changed in the current question
        # revision from the previous one is the explanation, reference
        # or explanation figure, delete the revision.
        previous_revision = Revision.objects.filter(question=revision.question,
                                                    pk__lt=revision.pk)\
                                            .order_by('pk')\
                                            .last()

        # Check if the question has the previous revision (i.e. that
        # has already been created) has the exact same explanation,
        # reference and explanation figure.
        if previous_revision and \
           previous_revision.explanation == revision.explanation and \
           previous_revision.reference == revision.reference and \
           previous_revision.explanation_figure.name == revision.explanation_figure.name:
            print("Skipping revision #{}".format(revision.pk))
            continue

        explanation = ExplanationRevision.objects\
                                         .create(question=revision.question,
                                                 submitter=revision.submitter,
                                                 text=revision.explanation,
                                                 reference=revision.reference)
        explanation.submission_date = revision.submission_date
        explanation.figure.name = revision.explanation_figure.name
        explanation.save()

        # Check if the only thing that has changed since the previous
        # revision si the explanation, reference or explanation
        # figure. If so, delete the previous revision.
        if previous_revision and \
           previous_revision.text == revision.text and \
           previous_revision.figure.name == revision.figure.name:
            changed_choices = False

            # If a choice was added/removed/changed, don't delete
            if revision.choice_set.count() != previous_revision.choice_set.count():
                continue

            choice_checks = []
            for choice in revision.choice_set.all():
                choice_check = previous_revision.choice_set.filter(text=choice.text,
                                                                   is_right=choice.is_right)\
                                                           .exists()
                choice_checks.append(choice_check)
            if not all(choice_checks):
                continue

            # If the to-be-deleted revision is the last, mark the one
            # before it as such.
            previous_revision.is_last = revision.is_last

            # Preserve approval meta information
            if revision.is_approved:
                previous_revision.is_approved = True
                previous_revision.approval_date = revision.approval_date
                previous_revision.approved_by = revision.approved_by
            previous_revision.save()

            # Link highlights to the previous revision
            Highlight.objects.filter(revision=revision)\
                             .update(revision=previous_revision)

            # Link answers to the previous revision
            for choice in revision.choice_set.all():
                if previous_revision.choice_set.filter(text=choice.text).count() > 1:
                    print("FUCK!", previous_revision.pk, revision.question.pk)
                previous_choice = previous_revision.choice_set.filter(text=choice.text).first()
                Answer.objects.filter(choice=choice)\
                              .update(choice=previous_choice)

            print("Deleting revision #{} of question #{}".format(revision.pk, revision.question.pk))

            # Aaaaaaaaaaand delete!
            revision.delete()

    for question in Question.objects.filter(is_deleted=False, explanation_revisions__isnull=False):
        first_explanation = question.explanation_revisions.order_by('pk').first()
        first_explanation.is_first = True
        first_explanation.save()

        last_explanation = question.explanation_revisions.order_by('pk').first()
        last_explanation.is_last = True
        last_explanation.save()

class Migration(migrations.Migration):

    dependencies = [
        ('exams', '0052_explanationrevision'),
    ]

    operations = [
        migrations.RunPython(create_explanation_revisions)
    ]
