# Generated by Django 3.2.4 on 2021-09-06 11:33

from django.db import migrations


def sanitise_supporting_orgs(apps, schema_editor):
    """Strip off special characters.

    After StrategicAction.supproting_orgs changed to CharField existing quotes and brackets within
    data doesn't make sense.
    Before: [""], ["BEIS", "DFT"]
    After : BEIS, DFT
    """
    removing_chars = r'[""]'
    SA = apps.get_model("supply_chains", "StrategicAction")

    for action in SA.objects.all():
        action.supporting_organisations = action.supporting_organisations.translate(
            str.maketrans("", "", removing_chars)
        )
        action.save()


def undo(apps, schema_editor):
    SA = apps.get_model("supply_chains", "StrategicAction")

    for action in SA.objects.all():
        sup_orgs = action.supporting_organisations

        if sup_orgs:
            orgs = sup_orgs.split(",")
            orgs = ['"' + x.strip() + '"' for x in orgs]

            action.supporting_organisations = "[" + ", ".join(orgs) + "]"

        else:
            action.supporting_organisations = r'[""]'

        action.save()


class Migration(migrations.Migration):

    dependencies = [
        ("supply_chains", "0025_alter_sa_supporting_orgs"),
    ]

    operations = [
        migrations.RunPython(sanitise_supporting_orgs, undo),
    ]
