# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-25 12:59
from __future__ import unicode_literals

import os

from django.db import migrations

from bulk_update.helper import bulk_update
from pootle.core.url_helpers import split_pootle_path


def clean_abs_file_paths(apps, schema_editor):
    """Replace wrong absolute store file paths by proper relative paths

    built based on store.pootle_path values.
    """
    store_model = apps.get_model("pootle_store.Store")
    store_qs = store_model.objects.select_related("filetype")
    for project in apps.get_model("pootle_project.Project").objects.all():
        if not project.treestyle == 'nongnu':
            continue
        stores = list(store_qs.filter(
            translation_project__project_id=project.id,
            file__startswith="/"))
        for store in stores:
            lang, prj, d, fn = split_pootle_path(store.pootle_path)
            store.file = os.path.join(prj, lang, d, fn)
        bulk_update(stores, update_fields=["file"])


class Migration(migrations.Migration):

    dependencies = [
       ('pootle_store', '0053_remove_unit_submitted'),
    ]

    operations = [
        migrations.RunPython(clean_abs_file_paths),
    ]
