# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-29 09:37


from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    def add_resulting_fragments(apps, schema_editor):
        """
        Fills the resulting_fragment column on Selections
        """
        Selection = apps.get_model('selections', 'Selection')
        Word = apps.get_model('annotations', 'Word')

        for selection in Selection.objects.filter(is_no_target=False):
            fragments = set()
            xml_ids = [w.xml_id for w in selection.words.all()]

            # Find the Fragments that have these xml_ids as targets
            for xml_id in xml_ids:
                words = Word.objects.filter(
                    sentence__fragment__document=selection.fragment.document,
                    xml_id=xml_id,
                    is_target=True)
                fragments.update([w.sentence.fragment for w in words])

            if fragments:
                result = []

                # Check if Fragment has the exact same Words as targets
                for fragment in fragments:
                    fragment_words = Word.objects.filter(sentence__fragment=fragment, is_target=True)
                    fragment_xml_ids = [w.xml_id for w in fragment_words]
                    if sorted(xml_ids) == sorted(fragment_xml_ids):
                        result.append(fragment)

                if len(result) == 1:
                    selection.resulting_fragment = result[0]
                    selection.save()

            """
                elif len(result) > 1:
                    print 'Multiple Fragments found:', selection.pk, [f.pk for f in result]
                else:
                    print 'No Fragment found for:', selection.pk
            else:
                print 'No Fragment found for:', selection.pk
            """

    def backwards(apps, schema_editor):
        pass

    dependencies = [
        ('annotations', '0028_source'),
        ('selections', '0008_preprocessfragment_resulting_fragment'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='preprocessfragment',
            name='resulting_fragment',
        ),
        migrations.AddField(
            model_name='selection',
            name='resulting_fragment',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='fragment_preprocess', to='annotations.Fragment'),
        ),

        migrations.RunPython(add_resulting_fragments, backwards),
    ]
