# Generated by Django 3.0.9 on 2020-08-13 14:06

from django.db import migrations, models

import aleksis.apps.chronos.util.date


def migrate_data(apps, schema_editor):
    LessonSubstitution = apps.get_model("chronos", "LessonSubstitution")
    ExtraLesson = apps.get_model("chronos", "ExtraLesson")

    db_alias = schema_editor.connection.alias

    for sub in LessonSubstitution.objects.using(db_alias).all():
        year = sub.lesson_period.lesson.validity.date_start.year
        if sub.week < int(sub.lesson_period.lesson.validity.date_start.strftime("%V")):
            year += 1
        sub.year = year
        sub.save()

    for extra_lesson in ExtraLesson.objects.using(db_alias).all():
        year = aleksis.apps.chronos.util.date.get_current_year()
        extra_lesson.year = year
        extra_lesson.save()


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0003_drop_image_cropping"),
        ("chronos", "0003_school_term_validity_fixes"),
    ]

    operations = [
        migrations.AddField(
            model_name="extralesson",
            name="year",
            field=models.IntegerField(
                default=aleksis.apps.chronos.util.date.get_current_year,
                verbose_name="Year",
            ),
        ),
        migrations.AddField(
            model_name="lessonsubstitution",
            name="year",
            field=models.IntegerField(
                default=aleksis.apps.chronos.util.date.get_current_year,
                verbose_name="Year",
            ),
        ),
        migrations.RunPython(migrate_data),
    ]
