# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-21 19:06
from __future__ import unicode_literals

from django.db import migrations

from pootle.core.batch import Batch
from pootle.core.user import get_system_user_id
from pootle_statistics.models import SubmissionTypes


def _update_reviewed(qs, unit_changes):
    values = qs.values_list("change", "reviewed_on", "reviewed_by")
    for change, reviewed_on, reviewed_by in values.iterator():
        unit_changes.filter(pk=change).update(
            reviewed_on=reviewed_on,
            reviewed_by=reviewed_by)


def _add_reviewed(qs, unit_changes):
    values = qs.values_list("id", "reviewed_on", "reviewed_by")

    def _create_method(unit, timestamp, user):
        return dict(
            unit_id=unit,
            changed_with=(
                SubmissionTypes.SYSTEM
                if user == get_system_user_id()
                else SubmissionTypes.WEB),
            reviewed_by_id=user,
            reviewed_on=timestamp)
    Batch(unit_changes).create(values, _create_method)


def set_change_reviewed(apps, schema_editor):
    units = apps.get_model("pootle_store.Unit").objects.all()
    unit_changes = apps.get_model("pootle_store.UnitChange").objects.all()
    _update_reviewed(
        units.filter(
            change__isnull=False).filter(reviewed_by__isnull=False),
        unit_changes)
    _add_reviewed(
        units.filter(
            change__isnull=True).filter(reviewed_by__isnull=False),
        unit_changes)


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_store', '0049_remove_unit_commented'),
    ]

    operations = [
        migrations.RunPython(set_change_reviewed),
    ]
