# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-26 09:10
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import leprikon.models.fields


def move_discounts(apps, schema_editor):

    ClubRegistration = apps.get_model('leprikon', 'ClubRegistration')
    ClubRegistrationDiscount = apps.get_model('leprikon', 'ClubRegistrationDiscount')

    for reg in ClubRegistration.objects.exclude(discount=0):
        discount = ClubRegistrationDiscount()
        discount.registration = reg
        if reg.canceled:
            discount.period = reg.club.periods.filter(end__gt=reg.created).last()
        else:
            discount.period = reg.club.periods.filter(end__gt=reg.created).first()
        discount.discount = reg.discount
        discount.explanation = reg.explanation
        discount.save()


class Migration(migrations.Migration):

    dependencies = [
        ('leprikon', '0009_cmsplugin_ptr'),
    ]

    operations = [
        migrations.CreateModel(
            name='ClubRegistrationDiscount',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('discount', leprikon.models.fields.PriceField(decimal_places=0, default=0, max_digits=10, verbose_name='discount')),
                ('explanation', models.CharField(blank=True, default='', max_length=250, verbose_name='discount explanation')),
                ('period', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='discounts', to='leprikon.ClubPeriod', verbose_name='period')),
                ('registration', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='discounts', to='leprikon.ClubRegistration', verbose_name='registration')),
            ],
            options={
                'ordering': ('period',),
                'verbose_name': 'club discount',
                'verbose_name_plural': 'club discounts',
            },
        ),
        migrations.AlterUniqueTogether(
            name='clubregistrationdiscount',
            unique_together=set([('registration', 'period')]),
        ),
        migrations.RunPython(move_discounts),
        migrations.RemoveField(
            model_name='clubregistration',
            name='discount',
        ),
        migrations.RemoveField(
            model_name='clubregistration',
            name='explanation',
        ),
    ]
