# Generated by Django 3.0.4 on 2020-03-31 18:36

from django.db import migrations


def load_cumulative_data(apps, schema_editor):
    Area = apps.get_model('model_api', 'Area')
    Covid19DataPoint = apps.get_model('model_api', 'Covid19DataPoint')
    Covid19CumulativeDataPoint = apps.get_model(
        'model_api',
        'Covid19CumulativeDataPoint')

    to_write = {}

    for d in Covid19DataPoint.objects.all():
        area_str = str(d.area)
        if area_str not in to_write or d.date > to_write[area_str]["data_point"].date:
            to_write[area_str] = {
                'area': d.area,
                'data_point': d,
            }

    for obj in to_write.values():
        c = Covid19CumulativeDataPoint(
            area=obj["area"],
            data_point=obj["data_point"])
        c.save()


def clear_cumulative_data(apps, schema_editor):
    Covid19CumulativeDataPoint = apps.get_model(
        'model_api',
        'Covid19CumulativeDataPoint')

    Covid19CumulativeDataPoint.objects.all().delete()


class Migration(migrations.Migration):

    dependencies = [
        ('model_api', '0003_covid19cumulativedatapoint'),
    ]

    operations = [
        migrations.RunPython(load_cumulative_data, clear_cumulative_data),
    ]
