# Generated by Django 2.2.2 on 2019-06-05 14:10

from django.db import migrations


country_map = {
    'SCHWEIZ': 'ch',
    'UNITED KINGDOM': 'gb',
    'DEUTSCHLAND': 'de'
}


def convert_data(apps, schema_editor):
    Customer = apps.get_model('customer.Customer')

    for customer in Customer.objects.exclude(address=''):
        lines = [l.strip() for l in customer.address.split('\n')]
        # auto detect country
        if lines[-1].upper() in country_map:
            country = country_map[lines[-1].upper()]
            lines = lines[:-1]
        else:
            country = 'DE'
        try:
            postal_code, city = lines[-1].split(' ', 1)
        except ValueError:
            state = lines[-1]
            lines = lines[:-1]
        else:
            state = ''
        assert len(lines) <= 6
        customer.customeraddress_set.create(
            name=lines[0],
            address_addition_1=lines[1] if len(lines) >= 4 else '',
            address_addition_2=lines[2] if len(lines) >= 5 else '',
            street=lines[-2],
            postal_code=lines[-1].split(' ', 1)[0],
            city=lines[-1].split(' ', 1)[1],
            state=state,
            country=country,
            invoice_address=True,
        )
        customer.name = lines[0]
        customer.save()


class Migration(migrations.Migration):

    dependencies = [
        ('customer', '0007_add_state'),
    ]

    operations = [
        migrations.RunPython(convert_data)
    ]
