# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-11 09:46
from __future__ import unicode_literals

from django.db import migrations


def old_recent_steps_lookup(FlowStep, step_uuid, rule_uuid, next_uuid):
    """
    The old way of looking up recent steps directly from flow step table
    """
    if rule_uuid:
        recent_steps = FlowStep.objects.filter(step_uuid=step_uuid, rule_uuid=rule_uuid, next_uuid=next_uuid)
    else:
        recent_steps = FlowStep.objects.filter(step_uuid=step_uuid, rule_uuid=None, next_uuid=next_uuid)

    recent_steps = recent_steps.prefetch_related('contact').order_by('-left_on')[:20]

    # discard steps by test contacts
    return [s for s in recent_steps if not s.contact.is_test][:10]


def do_populate(FlowStep, FlowPathRecentStep):
    # fetch all of the node->node path segments
    segments = list(FlowStep.objects.values_list('step_uuid', 'rule_uuid', 'next_uuid').distinct())
    if not segments:
        return

    print("Fetched %d unique flow path segments" % len(segments))
    num_segments = 0
    num_steps = 0

    for segment in segments:
        step_uuid, rule_uuid, next_uuid = segment
        steps = old_recent_steps_lookup(FlowStep, step_uuid, rule_uuid, next_uuid)

        from_uuid = rule_uuid or step_uuid
        to_uuid = next_uuid

        for step in steps:
            # some might already have been created by new model code
            FlowPathRecentStep.objects.get_or_create(from_uuid=from_uuid, to_uuid=to_uuid, step=step)

        num_segments += 1
        num_steps += len(steps)

        if num_segments % 500 == 0:
            print(" > Created %d recent step records for %d of %d segments" % (num_steps, num_segments, len(segments)))


def apply_as_migration(apps, schema_editor):
    FlowStep = apps.get_model('flows', 'FlowStep')
    FlowPathRecentStep = apps.get_model('flows', 'FlowPathRecentStep')

    do_populate(FlowStep, FlowPathRecentStep)


def apply_manual():
    from temba.flows.models import FlowStep, FlowPathRecentStep

    do_populate(FlowStep, FlowPathRecentStep)


class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0083_auto_20170113_0800'),
    ]

    operations = [
        migrations.RunPython(apply_as_migration)
    ]

# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-11 09:46
from __future__ import unicode_literals

from django.db import migrations


def old_recent_steps_lookup(FlowStep, step_uuid, rule_uuid, next_uuid):
    """
    The old way of looking up recent steps directly from flow step table
    """
    if rule_uuid:
        recent_steps = FlowStep.objects.filter(step_uuid=step_uuid, rule_uuid=rule_uuid, next_uuid=next_uuid)
    else:
        recent_steps = FlowStep.objects.filter(step_uuid=step_uuid, rule_uuid=None, next_uuid=next_uuid)

    recent_steps = recent_steps.prefetch_related('contact').order_by('-left_on')[:20]

    # discard steps by test contacts
    return [s for s in recent_steps if not s.contact.is_test][:10]


def do_populate(FlowStep, FlowPathRecentStep):
    # fetch all of the node->node path segments
    segments = list(FlowStep.objects.exclude(next_uuid=None).values_list('step_uuid', 'rule_uuid', 'next_uuid').distinct())
    if not segments:
        return

    print("Fetched %d unique flow path segments" % len(segments))
    num_segments = 0
    num_steps = 0

    for segment in segments:
        step_uuid, rule_uuid, next_uuid = segment
        steps = old_recent_steps_lookup(FlowStep, step_uuid, rule_uuid, next_uuid)

        from_uuid = rule_uuid or step_uuid
        to_uuid = next_uuid

        for step in steps:
            # some might already have been created by new model code
            FlowPathRecentStep.objects.get_or_create(from_uuid=from_uuid, to_uuid=to_uuid, step=step,
                                                     defaults={'left_on': step.left_on})

        num_segments += 1
        num_steps += len(steps)

        if num_segments % 500 == 0:
            print(" > Created %d recent step records for %d of %d segments" % (num_steps, num_segments, len(segments)))


def apply_as_migration(apps, schema_editor):
    FlowStep = apps.get_model('flows', 'FlowStep')
    FlowPathRecentStep = apps.get_model('flows', 'FlowPathRecentStep')

    do_populate(FlowStep, FlowPathRecentStep)


def apply_manual():
    from temba.flows.models import FlowStep, FlowPathRecentStep

    do_populate(FlowStep, FlowPathRecentStep)


class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0083_auto_20170116_0750'),
    ]

    operations = [
        migrations.RunPython(apply_as_migration)
    ]

Update migration to store left_on and ignore steps without a next_uuid