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

from django.db import migrations


def drop_stray_directories(apps, schema_editor):
    """Drop directories that belong to no existing TP."""
    Directory = apps.get_model("pootle_app.Directory")
    TP = apps.get_model("pootle_translationproject.TranslationProject")
    Language = apps.get_model("pootle_language.Language")


    dirs = Directory.objects.exclude(
        pootle_path="/"
    ).exclude(
        pootle_path__startswith="/goals/"
    ).exclude(
        pootle_path__startswith="/projects/"
    )

    language_codes = Language.objects.values_list("code", flat=True)

    for directory in dirs:
        directory_path_parts = directory.pootle_path.split("/")

        if len(directory_path_parts) < 4:
            continue

        directory_lang_code = directory_path_parts[1]

        if directory_lang_code in language_codes:
            tp_path = "/".join(directory_path_parts[:3] + [""])
            has_tp = TP.objects.filter(pootle_path=tp_path).exists()

            if not has_tp:
                Directory.objects.filter(
                    pootle_path__startswith=directory.pootle_path
                ).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('pootle_app', '0016_set_directory_tp_again'),
        ('pootle_translationproject', '0005_remove_empty_translationprojects'),
        ('pootle_language', '0002_case_insensitive_schema'),
    ]

    operations = [
        migrations.RunPython(drop_stray_directories),
    ]
