# Generated by Django 3.1 on 2020-10-14 00:33
from django.db import migrations, models, connection
from data.scripts.sql_loader import (
    load_bls_oes_to_sql,
    load_occupation_transitions_to_sql,
)


class Migration(migrations.Migration):
    """
    Update the model to have autofield to accomodate auto-incrementing ids and nullability on soc2 field.
    Add code to migrate data from data migration script into django model.
    """

    dependencies = [
        ("jobs", "0008_auto_20201006_AddStateData"),
    ]

    def forwards_source_data(apps, schema_editor):
        with connection.schema_editor() as my_schema_editor:
            print(f" show db {my_schema_editor.connection.alias}")
        print("Processing data from csv; This will take a few minutes.")
        # load_bls_oes_to_sql("")
        conn_info = str(schema_editor.connection.__dict__["connection"])
        print(conn_info)
        db_name = conn_info.split("dbname=")[1].split(" ")[0]
        print(db_name)

        load_occupation_transitions_to_sql(
            "data/occupation_transitions_public_data_set.csv",
            db_name,
        )
        print("done with forward load")

    def reverse_source_data(apps, schema_editor):
        print("removing source data")
        migrations.RunSQL([("drop table occupation_transition")])

    def forwards_func(apps, schema_editor):
        # alter fields for go-forward work
        migrations.AlterField(
            "OccupationTransitions",
            "id",
            models.AutoField(auto_created=True, primary_key=True),
        )
        migrations.AlterField(
            "OccupationTransitions", "soc2", models.CharField(max_length=7, null=True)
        )

    def reverse_func(apps, schema_editor):
        # alter fields for backward migration.
        migrations.AlterField(
            "OccupationTransitions", "id", models.IntegerField(primary_key=True)
        )
        migrations.AlterField(
            "OccupationTransitions", "soc2", models.CharField(max_length=7)
        )
        """
        
        """

        operations = [
            migrations.RunPython(forwards_source_data, reverse_source_data),
            migrations.RunPython(forwards_func, reverse_func),
            migrations.RunSQL(
                [
                    (
                        "insert into jobs_occupationtransitions (soc1, soc2, total_soc, pi, occleaveshare) select soc1, soc2, total_soc, pi, occleaveshare from occupation_transition"
                    )
                ],
                [("DELETE FROM jobs_occupationtransitions")],
            ),
        ]
