# Generated by Django 1.11.15 on 2018-11-19 18:42


from django.db import migrations, models


def migrate_has_ofac_restriction_data(apps, schema_editor):
    course_model = apps.get_model('publisher', 'Course')
    course_run_model = apps.get_model('publisher', 'CourseRun')
    for course in course_model.objects.all():
        course_runs = course_run_model.objects.filter(course=course)
        for course_run in course_runs:
            course_run.has_ofac_restrictions = course.has_ofac_restrictions
            course_run.save()


def reverse_migrate_has_ofac_restrictions_data(apps, schema_editor):
    """
    Reverting this to a higher level could result in a loss of data depending on time
    the change was in production.  This will take the state of the most recent Course Run available.
    """
    course_model = apps.get_model('publisher', 'Course')
    course_run_model = apps.get_model('publisher', 'CourseRun')
    for course in course_model.objects.all():
        course_runs = course_run_model.objects.filter(course=course).order_by('-start')
        if course_runs:
            course.has_ofac_restrictions = course_runs[0].has_ofac_restrictions
            course.save()


class Migration(migrations.Migration):

    dependencies = [
        ('publisher', '0068_auto_20181105_1630'),
    ]

    operations = [
        migrations.AddField(
            model_name='courserun',
            name='has_ofac_restrictions',
            field=models.BooleanField(
                default=False,
                verbose_name='Has OFAC Restriction Text'
            ),
        ),
        migrations.AddField(
            model_name='historicalcourserun',
            name='has_ofac_restrictions',
            field=models.BooleanField(
                default=False,
                verbose_name='Has OFAC Restriction Text'
            ),
        ),
        migrations.RunPython(
            migrate_has_ofac_restriction_data,
            reverse_migrate_has_ofac_restrictions_data
        ),
    ]
