# -*- coding: utf-8 -*-
"""
This migration promotes `m_payment_id` to a full alphanumeric field,
and lets PayFastOrder have a conventional primary key.
"""
# Generated by Django 1.11.8 on 2017-12-14 18:07
from __future__ import unicode_literals

import django
from django.db import migrations, models


if django.VERSION < (1, 8):  # Django 1.7 compatibility: RunPython.noop was added in 1.8.
    def noop(apps, schema_editor):
        return None


def preserve_old_m_payment_id_values(apps, schema_editor):
    """
    Preserve the old `m_payment_id` values into the new field.
    """
    PayFastOrder = apps.get_model('payfast', 'PayFastOrder')

    for order in PayFastOrder.objects.all():
        assert order.m_payment_id is None, order
        order.m_payment_id = str(order.pk)
        order.save()


class Migration(migrations.Migration):

    dependencies = [
        ('payfast', '0002_update_payfastorder_timestamp_fields'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='payfastorder',
            options={'verbose_name': 'PayFast order'},
        ),
        migrations.AlterField(
            model_name='payfastorder',
            name='amount_fee',
            field=models.DecimalField(blank=True, decimal_places=2, help_text='The total in fees which was deducted from the amount.', max_digits=15, null=True),
        ),

        # Convert the existing m_payment_id to a normal Django primary key.
        migrations.RenameField(
            model_name='payfastorder',
            old_name='m_payment_id',
            new_name='id',
        ),
        migrations.AlterField(
            model_name='payfastorder',
            name='id',
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),

        # Re-introduce m_payment_id as an alphanumeric
        migrations.AddField(
            model_name='payfastorder',
            name='m_payment_id',
            field=models.CharField(blank=True, help_text="Unique transaction ID on the receiver's system.", max_length=100, null=True, unique=True),
        ),
        migrations.RunPython(
            preserve_old_m_payment_id_values,
            reverse_code=(noop if django.VERSION < (1, 8) else
                          migrations.RunPython.noop),
        ),
    ]
