# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-11-08 21:27
from __future__ import unicode_literals

from django.db import migrations


def relink_or_drop_orphan_translationprojects(apps, schema_editor):
    """Relink or drop TPs with no project."""
    Project = apps.get_model("pootle_project.Project")
    TP = apps.get_model("pootle_translationproject.TranslationProject")

    for proj_key in set(TP.objects.values_list("project_id", flat=True)):
        if not Project.objects.filter(pk=proj_key).exists():
            for tp in TP.objects.filter(project_id=proj_key):
                proj_code = tp.pootle_path.split("/")[2]
                projects = Project.objects.filter(code=proj_code)

                if projects.exists():
                    tp.project = projects.first()
                    tp.save()
                else:
                    tp.delete()


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_translationproject', '0005_remove_empty_translationprojects'),
        ('pootle_project', '0014_just_rename_label_for_choice'),
    ]

    operations = [
        migrations.RunPython(relink_or_drop_orphan_translationprojects),
    ]
