# Generated by Django 3.0.4 on 2020-04-05 17:36

from django.db import migrations, models

ROOM_ONLY_COUNT = 0
ROOM_TYPE_COUNT_MAPPING = {
    "Комната": ROOM_ONLY_COUNT,
    "1-комнатная квартира": 1,
    "2-комнатная квартира": 2,
    "3-комнатная квартира": 3,
    "4-комнатная квартира": 4,
    "5-комнатная квартира": 5,
    "6-комнатная квартира": 6,
    "7-комнатная квартира": 7,
    "8-комнатная квартира": 8,
}
TYPE_TO_COUNT_MAPPING = [
    models.When(apartment_type=known_type, then=models.Value(associated_value))
    for known_type, associated_value in ROOM_TYPE_COUNT_MAPPING.items()
]


def fill_room_count_as_actual_property(apps, schema_editor):
    Rent = apps.get_model('apartments_analyzer', 'RentApartment')
    Sold = apps.get_model('apartments_analyzer', 'SoldApartments')
    for model in Rent, Sold:
        updated_count = (
            model.objects
                 .filter(total_rooms__isnull=True)
                 .annotate(
                    room_count=models.Case(
                        *TYPE_TO_COUNT_MAPPING,
                        default=models.Value(None),
                        output_field=models.IntegerField()
                    )
                 )
                 .update(total_rooms=models.F('room_count'))
            )
        print(f"Updated {updated_count} rows.")


class Migration(migrations.Migration):

    dependencies = [
        ('apartments_analyzer', '0033_auto_20200405_2035'),
    ]

    operations = [
        migrations.RunPython(
            fill_room_count_as_actual_property
        )
    ]
