# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import logging


# migrate measurement objects by adding back the raw analysis result field, which
# holds the geometric mean of all non excluded ites. since the actual result field
# takes predilution into account, we need to reverse that step here.
def forward_migration(apps, schema_editor):
    from django.db.transaction import atomic
    from samples.models import Sample

    with atomic():
        # grab the 'new' version of our Measurement model
        Measurement = apps.get_model('measurements', 'Measurement')
        existing_measurements = Measurement.objects.all()
        for m in existing_measurements:

            # django migrations works with some fake objects, which do not allow access to custom properties
            # hence we need to lookup the sample on our own to grab the total dilution factor

            s = Sample.objects.get(id=m.sample.pk)
            s_fac = s.total_dilution

            if s_fac <= 0:
                logging.debug('invalid dilution factor for sample {0} fac={1}'.format(s, s_fac))
                continue

            # if result is something, divide by dilution factor to get
            # the original analysis result
            if m.result is not None:
                m.analysis_result = m.result / s_fac
            else:
                m.analysis_result = None

            m.save()


class Migration(migrations.Migration):
    dependencies = [
        ('measurements', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='measurement',
            name='analysis_result',
            field=models.FloatField(null=True, blank=True, verbose_name='analysis result'),
            preserve_default=True,
        ),
        migrations.RunPython(
            forward_migration,
        )
    ]

