# Generated by Django 1.11.13 on 2018-08-26 15:58

from itertools import count
from django.db import migrations, models
import django.db.models.deletion


def create_school_year_divisions(apps, schema_editor):
    Course = apps.get_model('leprikon', 'Course')
    CourseDiscount = apps.get_model('leprikon', 'CourseDiscount')
    SchoolYearDivision = apps.get_model('leprikon', 'SchoolYearDivision')
    SchoolYearPeriod = apps.get_model('leprikon', 'SchoolYearPeriod')
    new_period_ids = {}
    new_period_ids_fuzzy = {}
    school_year_division_ids = {}
    for course in Course.objects.order_by('id').iterator():
        key = tuple(course.periods.order_by('id').values_list('id', flat=True))
        if key not in school_year_division_ids:
            name = course.unit
            counter = count(2)
            while SchoolYearDivision.objects.filter(
                school_year_id=course.school_year_id,
                name=name,
            ).exists():
                name='{course_unit} {c}'.format(course_unit=course.unit, c=next(counter))
            school_year_division = SchoolYearDivision.objects.create(
                school_year_id=course.school_year_id,
                name=name,
                period_name=course.unit,
            )
            for period in course.periods.all():
                old_period_id = period.id
                period.id, period.pk = None, None
                period.school_year_division = school_year_division
                period.save()
                new_period_ids[(key, old_period_id)] = period.id
                new_period_ids_fuzzy[(key, period.name)] = period.id
            school_year_division_ids[key] = school_year_division.id
        course.school_year_division_id = school_year_division_ids[key]
        course.save()
        # fix discounts
        for discount in CourseDiscount.objects.filter(
            registration__subject_id=course.id
        ).select_related('period', 'registration'):
            old_period = discount.period
            discount.period = None
            discount.period_id = new_period_ids.get((key, old_period.id))
            if discount.period_id is None:
                discount.period_id = new_period_ids_fuzzy.get((key, old_period.name))
            discount.save()
    # delete original periods
    SchoolYearPeriod.objects.filter(school_year_division=None).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('leprikon', '0014_variable_symbol'),
    ]

    operations = [
        migrations.CreateModel(
            name='SchoolYearDivision',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=150, verbose_name='division name')),
                ('period_name', models.CharField(max_length=150, verbose_name='period name')),
                ('school_year', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='divisions', to='leprikon.SchoolYear', verbose_name='school year')),
            ],
            options={
                'ordering': ('name',),
                'verbose_name': 'school year division',
                'verbose_name_plural': 'school year divisions',
            },
        ),
        migrations.AlterUniqueTogether(
            name='schoolyeardivision',
            unique_together=set([('school_year', 'name')]),
        ),
        migrations.AddField(
            model_name='course',
            name='school_year_division',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='courses', to='leprikon.SchoolYearDivision', verbose_name='school year division'),
        ),
        migrations.AddField(
            model_name='schoolyearperiod',
            name='school_year_division',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='periods', to='leprikon.SchoolYearDivision', verbose_name='school year division'),
        ),
        migrations.RunPython(create_school_year_divisions),
    ]
