# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-04 14:04
from __future__ import unicode_literals

import logging

from django.db import migrations

from pootle_data.store_data import StoreDataTool
from pootle_data.tp_data import TPDataTool


logger = logging.getLogger(__name__)


def fix_empty_wordcounts(apps, schema_editor):
    unit_sources = apps.get_model("pootle_store.UnitSource").objects
    Store = apps.get_model("pootle_store.Store")
    TranslationProject = apps.get_model("pootle_translationproject.TranslationProject")
    unit_sources = unit_sources.filter(source_wordcount=1).filter(unit__source_f__regex="^$")
    stores = set(unit_sources.values_list("unit__store", flat=True).distinct())
    tps = set(unit_sources.values_list("unit__store__translation_project", flat=True).distinct())
    unit_sources.update(source_wordcount=0)
    for store in Store.objects.filter(id__in=stores).iterator():
        logger.debug("Updating stats for Store: %s" % store.pootle_path)
        StoreDataTool(store).update()
    for tp in TranslationProject.objects.filter(id__in=tps).iterator():
        logger.debug("Set stats for TP: %s" % tp.pootle_path)
        TPDataTool(tp).update()


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_store', '0031_remove_suggestion_translator_comment_f'),
        ('pootle_data', '0007_add_store_and_tp_data_again'),
    ]

    operations = [
        migrations.RunPython(fix_empty_wordcounts),
    ]
