# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-02 07:04
from __future__ import unicode_literals

from django.db import migrations
from django.db.models import functions, Case, IntegerField, Sum, When


def set_user_scores(apps, schema_editor):
    from accounts.models import User
    from pootle_statistics.models import TranslationActionCodes

    UserTPScore = apps.get_model("pootle_score.UserTPScore")
    scorelogs = apps.get_model("pootle_statistics.ScoreLog").objects.exclude(
        user__username__in=User.objects.META_USERS)
    scorelogs = scorelogs.annotate(
        day=functions.TruncDay("creation_time")).values(
            "day", "user", "submission__translation_project").annotate(
                score=Sum("score_delta"),
                suggested=Sum(
                    Case(
                        When(
                            action_code=TranslationActionCodes.SUGG_ADDED,
                            then='wordcount'),
                        default=0,
                        output_field=IntegerField())),
                translated=Sum(
                    Case(
                        When(
                            translated_wordcount__isnull=False,
                            then='translated_wordcount'),
                        default=0,
                        output_field=IntegerField())),
                reviewed=Sum(
                    Case(
                        When(
                            action_code__in=[
                                TranslationActionCodes.SUGG_REVIEWED_ACCEPTED,
                                TranslationActionCodes.REVIEWED,
                                TranslationActionCodes.EDITED],
                            translated_wordcount__isnull=True,
                            then='wordcount'),
                        default=0,
                        output_field=IntegerField())))
    UserTPScore.objects.bulk_create(
        UserTPScore(
            date=score["day"],
            user_id=score["user"],
            tp_id=score["submission__translation_project"],
            score=score["score"],
            reviewed=score["reviewed"],
            suggested=score["suggested"],
            translated=score["translated"])
        for score in scorelogs.iterator())


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_score', '0001_initial'),
        ('pootle_statistics', '0005_index_ordering')
    ]

    operations = [
        migrations.RunPython(set_user_scores),
    ]
