from django.db import migrations

from ipfabric_netbox.utilities.transform_map import do_change
from ipfabric_netbox.utilities.transform_map import RelationshipRecord
from ipfabric_netbox.utilities.transform_map import TransformMapRecord


TRANSFORM_MAP_CHANGES = (
    TransformMapRecord(
        source_endpoint="/technology/platforms/stack/members",
        target_model="dcim.virtualchassis",
        relationships=(
            RelationshipRecord(
                source_model="dcim.device",
                target_field="master",
                old_template="{% set DEVICE = dcim.Device.objects.filter(serial=object.sn).first() %}{% if DEVICE %}{{ DEVICE.pk }}{% endif %}",
                new_template="{% set DEVICE = dcim.Device.objects.filter(serial=object.sn).first() %}{% if DEVICE %}{% if object.master is defined and object.master %}{% set VC_NAME = object.master %}{% else %}{% set VC_NAME = object.hostname %}{% endif %}{% set VIRTUAL_CHASSIS = dcim.VirtualChassis.objects.filter(name=VC_NAME).first() %}{% if VIRTUAL_CHASSIS and DEVICE.virtual_chassis == VIRTUAL_CHASSIS %}{{ DEVICE.pk }}{% endif %}{% endif %}",
            ),
        ),
    ),
)


def forward_transform_maps_change(apps, schema_editor):
    """Replace old template with updated version."""
    do_change(apps, schema_editor, changes=TRANSFORM_MAP_CHANGES, forward=True)


def revert_transform_maps_change(apps, schema_editor):
    """Revert template back to the previous exact template."""
    do_change(apps, schema_editor, changes=TRANSFORM_MAP_CHANGES, forward=False)


class Migration(migrations.Migration):
    dependencies = [
        ("ipfabric_netbox", "0026_update_platform_templates"),
    ]

    operations = [
        migrations.RunPython(
            forward_transform_maps_change,
            revert_transform_maps_change,
        ),
    ]
