# Generated by Django 3.1 on 2020-08-27 10:08
import re, requests

from django.db import migrations
from pyproj import Transformer
from django.conf import settings

transformer = Transformer.from_crs('epsg:3879', 'epsg:4326')


def sync_street_address(self):
    self.street_address = f'{self.street} {self.housenumber} {self.unit or ""}'.strip()


def forwards(apps, schema_editor):
    if settings.TEST:
        return
    Address = apps.get_model('fvh_courier', 'Address')

    response = requests.get('https://kartta.hel.fi/ws/geoserver/avoindata/wfs?version=1.1.0&request=GetFeature&typeName=avoindata:Osoiteluettelo_piste_rekisteritiedot&outputformat=json')
    addresses = response.json()

    addresses_out = []
    for f in addresses['features']:
        props = f['properties']
        if props['osoitenumero']:
            if re.fullmatch(r'\d+-\d+', props['osoitenumero']):
                parts = props['osoitenumero'].split('-')
                nrs = list(range(int(parts[0]), int(parts[1]) + 1, 2))
            else:
                nrs = [props['osoitenumero']]
            coord = transformer.transform(props['n'], props['e'])
            for nr in nrs:
                addresses_out.append(Address(**{
                    "street": props['katunimi'],
                    "housenumber": str(nr),
                    "street_address": props['katuosoite'],
                    "postal_code": props['postinumero'],
                    "city": 'Helsinki',
                    "country": 'Finland',
                    "official": True,
                    "lat": coord[0],
                    "lon": coord[1]
                }))

    Address.objects.bulk_create(addresses_out)


class Migration(migrations.Migration):

    dependencies = [
        ('fvh_courier', '0042_address_official'),
    ]

    operations = [
        migrations.RunPython(forwards, lambda apps, schema_editor: None)
    ]
