# Generated by Django 3.1 on 2020-09-23 20:19

from django.db import migrations


def create_review_categories(apps, schema_editor):
    Event = apps.get_model("event", "Event")
    EventSettings = apps.get_model("event", "Event_SettingsStore")
    ReviewScoreCategory = apps.get_model("submission", "ReviewScoreCategory")
    ReviewScore = apps.get_model("submission", "ReviewScore")
    Review = apps.get_model("submission", "Review")
    for event in Event.objects.filter(score_categories__isnull=True):
        min_score = EventSettings.objects.filter(
            object=event, key="review_min_score"
        ).first()
        max_score = EventSettings.objects.filter(
            object=event, key="review_max_score"
        ).first()

        main_category = ReviewScoreCategory.objects.create(event=event, name="Score")
        min_score = int(min_score.value) if min_score else 0
        max_score = int(max_score.value) if max_score else 1
        scores = []
        previous_scores = EventSettings.objects.filter(
            object=event, key__startswith="review_score_name"
        )
        for counter in range(abs(max_score - min_score) + 1):
            value = min_score + counter
            name = [
                setting
                for setting in previous_scores
                if setting.key == f"review_score_name_{value}"
            ]
            if name:
                name = name[0].value
            label = name or str(value)
            scores.append(ReviewScore(value=value, label=label, category=main_category))

        ReviewScore.objects.bulk_create(scores)
        scores = {
            score.value: score
            for score in ReviewScore.objects.filter(category=main_category)
        }

        through_model = ReviewScore._meta.get_field("reviews").through
        relations = []

        for review in Review.objects.all().filter(
            score__isnull=False, submission__event=event
        ):
            score = scores.get(review.score)
            if not score:
                score = ReviewScore.objects.create(
                    value=review.score, label=str(review.score), category=main_category
                )
                scores[review.score] = score

            relations.append(
                through_model(
                    review_id=review.id,
                    reviewscore_id=score.id,
                )
            )

        through_model.objects.bulk_create(relations)


class Migration(migrations.Migration):

    dependencies = [
        ("submission", "0049_review_score_categories"),
    ]

    operations = [
        migrations.RunPython(create_review_categories, migrations.RunPython.noop)
    ]
