# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-07-02 19:16
import os

from django.db import migrations, models

from ESSArch_Core.ip.models import InformationPackage as IP
from ESSArch_Core.util import find_destination, normalize_path


def get_structure(ip):
    ip_profile_rel = ip.profileip_set.get(profile__profile_type='aip')
    return ip_profile_rel.profile.structure


def forward(apps, schema_editor):
    InformationPackage = apps.get_model("ip", "InformationPackage")
    db_alias = schema_editor.connection.alias

    for ip in InformationPackage.objects.using(db_alias).filter(package_type=IP.AIP, sip_objid='').iterator():
        ip.sip_objid = ip.object_identifier_value
        if ip.state in ('Prepared', 'Receiving'):
            ip.sip_path = ip.sip_objid
        else:
            structure = get_structure(ip)
            content_dir, content_name = find_destination('content', structure)
            content_path = os.path.join(content_dir, content_name)
            ip.sip_path = normalize_path(os.path.join(content_path, ip.sip_objid))
        ip.save()


class Migration(migrations.Migration):
    dependencies = [
        ('ip', '0073_auto_20180529_1429'),
    ]

    operations = [
        migrations.AddField(
            model_name='informationpackage',
            name='sip_objid',
            field=models.CharField(default='', max_length=255),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='informationpackage',
            name='sip_path',
            field=models.CharField(default='', max_length=255),
            preserve_default=False,
        ),
        migrations.RunPython(forward, migrations.RunPython.noop),
    ]
