# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-01 08:04
from __future__ import unicode_literals

from django.db import migrations
from django.db.models import F


WEB_FLAG = 1
SUGG_ACCEPT_FLAG = 3
STATE_FIELD_FLAG = 3


def _assoc_state_accept_suggestion_subs(apps):
    subs = apps.get_model("pootle_statistics.Submission").objects.all()
    suggestions = apps.get_model("pootle_store.Suggestion").objects
    accepted = suggestions.filter(state__name="accepted").values(
        "review_time", "pk", "unit_id", "reviewer")
    state_acc = subs.filter(
        type=SUGG_ACCEPT_FLAG).filter(field=STATE_FIELD_FLAG)

    for suggestion in accepted.iterator():
        suggestion["submitter"] = suggestion["reviewer"]
        suggestion["creation_time"] = suggestion["review_time"]
        suggestion_id = suggestion["pk"]
        del suggestion["review_time"]
        del suggestion["reviewer"]
        del suggestion["pk"]
        state_acc.filter(**suggestion).update(suggestion_id=suggestion_id)


def _delete_redundant_accept_sugg_subs(apps):
    subs = apps.get_model("pootle_statistics.Submission").objects
    sugg_acc = subs.filter(type=SUGG_ACCEPT_FLAG)

    # these appear to be caused by dupes

    # no suggestion
    sugg_acc.filter(suggestion__isnull=True).delete()

    # review time doesnt match
    sugg_acc.exclude(
        creation_time=F("suggestion__review_time")).delete()

    # reviewer doesnt match
    sugg_acc.exclude(
        submitter=F("suggestion__reviewer")).delete()


def convert_accept_suggestion_subs(apps, schema_editor):
    subs = apps.get_model("pootle_statistics.Submission").objects

    # clear up existing subs first
    _assoc_state_accept_suggestion_subs(apps)
    _delete_redundant_accept_sugg_subs(apps)

    # convert to SubmissionTypes.WEB
    subs.filter(type=SUGG_ACCEPT_FLAG).update(type=WEB_FLAG)


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_statistics', '0018_remove_submission_store'),
        ('pootle_store', '0045_remove_suggestion_tmp_state'),
    ]

    operations = [
        migrations.RunPython(convert_accept_suggestion_subs),
    ]
