# Generated by Django 1.9.13 on 2018-01-05 12:45

from django.db import migrations


def set_is_city_part(apps, schema_editor):
    CourseDiscount = apps.get_model('leprikon', 'CourseDiscount')
    SchoolYearPeriod = apps.get_model('leprikon', 'SchoolYearPeriod')
    for discount in CourseDiscount.objects.all():
        periods = list(SchoolYearPeriod.objects.filter(
            courses__registrations__id=discount.registration_id,
            start__lte=discount.period.end,
            end__gte=discount.period.start,
        ))
        if discount.period not in periods:
            if periods:
                discount.period = periods[0]
                discount.save()
                print('Fixed period for discount %d' % discount.id)
            else:
                print('Failed to fix period for discount %d' % discount.id)


class Migration(migrations.Migration):

    dependencies = [
        ('leprikon', '0005_subjectregistration_variable_symbol'),
    ]

    operations = [
        migrations.RunPython(set_is_city_part),
    ]
