# Generated by Django 2.2.2 on 2019-06-05 15:27

from django.db import migrations


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


def parse_address(s):
    lines = [l.strip() for l in s.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
    return dict(
        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,
    )

def convert_data(apps, schema_editor):
    Invoice = apps.get_model('billing.Invoice')

    for invoice in Invoice.objects.all():
        for field_name, value in parse_address(invoice.old_recipient).items():
            setattr(invoice, f'recipient_{field_name}', value)
        for field_name, value in parse_address(invoice.old_sender).items():
            setattr(invoice, f'sender_{field_name}', value)
        invoice.save()


class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0004_new_address_fields'),
    ]

    operations = [
        migrations.RunPython(convert_data),
    ]
