# Generated by Django 3.1.7 on 2021-03-30 06:49

from datetime import date, timedelta

from django.db import migrations
from django.db.models import Count, Q

SCOPE_GLOBAL = 0
SCOPE_USER = 4
ACTION_CHANGE = 2
ACTION_COMMENT = 3
ACTION_NEW = 5
ACTION_AUTO = 6
ACTION_ACCEPT = 7
ACTION_REVERT = 8
ACTION_UPLOAD = 9
ACTION_REPLACE = 27
ACTION_BULK_EDIT = 32
ACTION_APPROVE = 36
ACTION_MARKED_EDIT = 37
ACTION_SCREENSHOT_ADDED = 57
ACTION_SCREENSHOT_UPLOADED = 58
ACTION_SUGGESTION = 4
ACTIONS_CONTENT = {
    ACTION_CHANGE,
    ACTION_NEW,
    ACTION_AUTO,
    ACTION_ACCEPT,
    ACTION_REVERT,
    ACTION_UPLOAD,
    ACTION_REPLACE,
    ACTION_BULK_EDIT,
    ACTION_APPROVE,
    ACTION_MARKED_EDIT,
}


def add_missing_user(apps, schema_editor):
    Metric = apps.get_model("metrics", "Metric")
    User = apps.get_model("weblate_auth", "User")
    db_alias = schema_editor.connection.alias

    try:
        oldest = (
            Metric.objects.using(db_alias)
            .filter(scope=SCOPE_GLOBAL)
            .order_by("-date")[0]
            .date
        )
    except IndexError:
        return
    days = (date.today() - oldest).days

    users = User.objects.using(db_alias).filter(is_active=True)
    metrics = []

    for offset in range(days + 1):
        current = oldest + timedelta(days=offset)
        for user in users:
            data = user.change_set.filter(
                timestamp__date=current - timedelta(days=1)
            ).aggregate(
                changes=Count("id"),
                comments=Count("id", filter=Q(action=ACTION_COMMENT)),
                suggestions=Count("id", filter=Q(action=ACTION_SUGGESTION)),
                translations=Count("id", filter=Q(action__in=ACTIONS_CONTENT)),
                screenshots=Count(
                    "id",
                    filter=Q(
                        action__in=(
                            ACTION_SCREENSHOT_ADDED,
                            ACTION_SCREENSHOT_UPLOADED,
                        )
                    ),
                ),
            )
            metrics.extend(
                [
                    Metric(
                        scope=SCOPE_USER,
                        relation=user.pk,
                        name=name,
                        value=value,
                        date=current,
                    )
                    for name, value in data.items()
                ]
            )

    Metric.objects.using(db_alias).bulk_create(metrics, ignore_conflicts=True)


class Migration(migrations.Migration):

    dependencies = [
        ("metrics", "0004_auto_20210330_0633"),
        ("trans", "0130_glossary_target"),
        ("weblate_auth", "0013_rename_sources_group"),
    ]

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