# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-22 13:43
from __future__ import unicode_literals

import logging
import time

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

logger = logging.getLogger(__name__)


def _update_submitted(qs, unit_changes):
    values = qs.values_list("change", "submitted_on", "submitted_by")
    for change, submitted_on, submitted_by in values.iterator():
        unit_changes.filter(pk=change).update(
            submitted_on=submitted_on,
            submitted_by=submitted_by)


def _add_submitted(qs, unit_changes):
    values = qs.values_list("id", "submitted_on", "submitted_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),
            submitted_by_id=user,
            submitted_on=timestamp)
    Batch(unit_changes).create(values, _create_method)


def set_change_submitted(apps, schema_editor):
    units = apps.get_model("pootle_store.Unit").objects.all()
    unit_changes = apps.get_model("pootle_store.UnitChange").objects.all()
    units_with_submitter = units.filter(
        submitted_by__isnull=False).filter(submitted_on__isnull=False)
    _update_submitted(
        units_with_submitter.filter(change__isnull=False),
        unit_changes)
    _add_submitted(
        units_with_submitter.filter(change__isnull=True),
        unit_changes)


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_store', '0051_remove_unit_reviewed'),
    ]

    operations = [
        migrations.RunPython(set_change_submitted),
    ]
