# Generated by Django 3.1.7 on 2021-03-19 14:42

from datetime import date

from django.db import migrations

ATTRMAP = (
    ("suggested", "suggestions"),
    ("translated", "translations"),
    ("uploaded", "screenshots"),
    ("commented", "comments"),
)


def migrate_user_metrics(apps, schema_editor):
    Profile = apps.get_model("accounts", "Profile")
    Metric = apps.get_model("metrics", "Metric")
    db_alias = schema_editor.connection.alias
    # Date reasonably in the past to keep the past metrics, but avoid influencing recent ones
    migrate_date = date(2020, 1, 1)
    create = []
    for profile in Profile.objects.using(db_alias).iterator():
        for origin, target in ATTRMAP:
            value = getattr(profile, origin)
            if value:
                create.append(
                    Metric(
                        date=migrate_date,
                        scope=4,  # SCOPE_USER
                        relation=profile.user_id,
                        name=target,
                        value=value,
                    )
                )

    if create:
        Metric.objects.bulk_create(create)


class Migration(migrations.Migration):

    dependencies = [
        ("metrics", "0001_initial"),
        ("accounts", "0013_auto_20210217_1653"),
    ]

    operations = [
        migrations.RunPython(
            migrate_user_metrics, migrations.RunPython.noop, elidable=True
        ),
    ]
