# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-27 20:51
from __future__ import unicode_literals

from django.db import migrations


def migrate_locations(apps, schema_editor):
    Property = apps.get_model('vacayo', 'Property')
    Location = apps.get_model('vacayo', 'Location')

    for property in Property.objects.all():
        if not property.location:
            # Reconstruct the full address
            address = property.address1

            if property.address2:
                address += ' ' + property.address2

            if property.city:
                address += ' ' + property.city

            if property.state:
                address += ' ' + property.state

            if property.zip_code:
                address += ' ' + property.zip_code

            # Create the location object (it will re-constitute the address parts and geo coordinates)
            location = Location.objects.create(
                _address=address
            )

            # Fill in any missing data
            if not location.address1:
                location.address1 = property.address1

            if not location.address2:
                location.address2 = property.address2

            if not location.city:
                location.city = property.city

            if not location.zip_code:
                location.zip_code = property.zip_code

            location.save()

            property.location = location
            property.save()


class Migration(migrations.Migration):

    dependencies = [
        ('vacayo', '0013_auto_20171027_2016'),
    ]

    operations = [
        migrations.RunPython(migrate_locations),
    ]
