import json

from django.db import migrations


STUDENT_IMPORT_TABLES = [
    "tt_student",
    "tt_student_academic_term",
    "tt_student_pos",
    "tt_student_pos_module",
]


def add_tt_student(apps, schema_editor):
    setting_model = apps.get_model("api", "TtSetting")
    setting = setting_model.objects.filter(param="import_tables").first()
    if not setting:
        return

    try:
        tables = json.loads(setting.value)
    except (TypeError, ValueError):
        tables = []

    changed = False

    for table in STUDENT_IMPORT_TABLES:
        if table not in tables:
            tables.append(table)
            changed = True

    if changed:
        setting.value = json.dumps(tables)
        setting.save(update_fields=["value"])


def remove_tt_student(apps, schema_editor):
    setting_model = apps.get_model("api", "TtSetting")
    setting = setting_model.objects.filter(param="import_tables").first()
    if not setting:
        return

    try:
        tables = json.loads(setting.value)
    except (TypeError, ValueError):
        return

    changed = False

    for table in STUDENT_IMPORT_TABLES:
        if table in tables:
            tables.remove(table)
            changed = True

    if changed:
        setting.value = json.dumps(tables)
        setting.save(update_fields=["value"])


class Migration(migrations.Migration):
    dependencies = [
        ("api", "0106_ttpos_student_ttstudentpathway_ttstudent_pathway"),
    ]

    operations = [
        migrations.RunPython(add_tt_student, remove_tt_student),
    ]
