# Generated by Django 1.11.12 on 2018-05-29 14:38
from __future__ import unicode_literals

from django.db import migrations


def get_descendant_ids(model_class, root_id):
    """
    Returns the a generator of primary keys which represent
    descendants of the given plugin ID (root_id)
    """
    ids = (
        model_class
        .objects
        .filter(parent=root_id)
        .order_by('position')
        .values_list('pk', flat=True)
    )

    for child_id in ids:
        yield child_id

        for child_id in get_descendant_ids(model_class, child_id):
            yield child_id


def set_plugin_absolute_position(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    CMSPlugin = apps.get_model('cms', 'CMSPlugin')
    Placeholder = apps.get_model('cms', 'Placeholder')
    placeholders = Placeholder.objects.using(db_alias).all()
    all_languages = (
        CMSPlugin
        .objects
        .using(db_alias)
        .values_list('language', flat=True)
        .distinct()
    )

    for placeholder in placeholders:
        for language in all_languages:
            position = 1
            plugins = placeholder.cmsplugin_set.filter(language=language)
            root_plugin_ids = (
                plugins
                .filter(parent__isnull=True)
                .order_by('position')
                .values_list('pk', flat=True)
            )
            for root_id in root_plugin_ids:
                plugins.filter(pk=root_id).update(position=position)
                position +=1

                for desc_id in get_descendant_ids(CMSPlugin, root_id=root_id):
                    plugins.filter(pk=desc_id).update(position=position)
                    position += 1


class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0023_placeholder_source_field'),
    ]

    operations = [
        migrations.RunPython(set_plugin_absolute_position),
    ]
