# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-28 11:31
from __future__ import unicode_literals

import functools
import logging
from hashlib import md5

from django.conf import settings
from django.db import migrations
from django.utils.encoding import force_bytes

from pootle.core.batch import Batch
from pootle.core.delegate import wordcount
from pootle_misc.util import import_func
from pootle_store.fields import to_python
from pootle_store.utils import UnitWordcount


BATCH_SIZE = 500

logger = logging.getLogger(__name__)


def unit_source_update(counter, unit_source):
    unit_source.source_hash = md5(
        force_bytes(unit_source.unit.source_f)).hexdigest()
    unit_source.source_length = len(unit_source.unit.source_f)
    unit_source.source_wordcount = max(
        1, (counter.count_words(to_python(unit_source.unit.source_f)) or 0))
    return unit_source


def set_unit_source_data(apps, schema_editor):
    from pootle_store.models import Unit
    UnitSource = apps.get_model(
        "pootle_store.UnitSource")
    counter = wordcount.get(Unit)
    unit_sources = (
        UnitSource.objects.select_related('unit')
                          .filter(source_wordcount=0)
                          .only("unit__source_f", "id")
                          .order_by("id"))
    Batch(unit_sources, batch_size=BATCH_SIZE).update(
        unit_sources,
        update_method=functools.partial(unit_source_update, counter),
        update_fields=[
            'source_hash',
            'source_length',
            'source_wordcount'])


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_store', '0054_clean_abs_file_paths'),
    ]

    operations = [
        migrations.RunPython(set_unit_source_data),
    ]
