# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-09 01:54
from __future__ import unicode_literals

from django.db import migrations, models


def reassociate_labels_to_views(apps, schema_editor):
    db_alias = schema_editor.connection.alias

    PropertyView = apps.get_model('seed', 'PropertyView')
    ThroughModel = PropertyView.labels.through
    records = []
    property_views = PropertyView.objects.using(db_alias).all()\
        .select_related('property').prefetch_related('property__labels')
    for p_view in property_views:
        for label in p_view.property.labels.all():
            records.append(ThroughModel(propertyview=p_view, statuslabel=label))
    ThroughModel.objects.bulk_create(records)
    # Free memory
    del property_views

    TaxLotView = apps.get_model('seed', 'TaxLotView')
    ThroughModel = TaxLotView.labels.through
    records = []
    taxlot_views = TaxLotView.objects.using(db_alias).all()\
        .select_related('taxlot').prefetch_related('taxlot__labels')
    for tl_view in taxlot_views:
        for label in tl_view.taxlot.labels.all():
            records.append(ThroughModel(taxlotview=tl_view, statuslabel=label))
    ThroughModel.objects.bulk_create(records)
    # Free memory
    del taxlot_views


class Migration(migrations.Migration):

    dependencies = [
        ('seed', '0103_auto_20190505_0731'),
    ]

    operations = [
        migrations.AddField(
            model_name='propertyview',
            name='labels',
            field=models.ManyToManyField(to='seed.StatusLabel'),
        ),
        migrations.AddField(
            model_name='taxlotview',
            name='labels',
            field=models.ManyToManyField(to='seed.StatusLabel'),
        ),
        migrations.RunPython(reassociate_labels_to_views),
        migrations.RemoveField(
            model_name='taxlot',
            name='labels',
        ),
        migrations.RemoveField(
            model_name='property',
            name='labels',
        ),
    ]
