# Generated by Django 3.2.19 on 2023-05-19 03:44

from django.db import migrations

from InvenTree.helpers import normalize


def update_supplier_part_units(apps, schema_editor):
    """Migrate existing supplier part units to new field"""

    SupplierPart = apps.get_model('company', 'SupplierPart')

    supplier_parts = SupplierPart.objects.all()

    for sp in supplier_parts:
        pack_size = normalize(sp.pack_size)
        sp.pack_quantity = str(pack_size)
        sp.pack_quantity_native = pack_size
        sp.save()

    if supplier_parts.count() > 0:
        print(f"Updated {supplier_parts.count()} supplier part units")


def reverse_pack_quantity(apps, schema_editor):
    """Reverse the migrations"""

    SupplierPart = apps.get_model('company', 'SupplierPart')

    supplier_parts = SupplierPart.objects.all()

    for sp in supplier_parts:
        sp.pack_size = sp.pack_quantity_native
        sp.save()

    if supplier_parts.count() > 0:
        print(f"Updated {supplier_parts.count()} supplier part units")

class Migration(migrations.Migration):

    dependencies = [
        ('company', '0059_supplierpart_pack_units'),
        ('part', '0111_auto_20230521_1350'),
    ]

    operations = [
        migrations.RunPython(
            code=update_supplier_part_units,
            reverse_code=reverse_pack_quantity,
        )
    ]
