"""Make enum non-native

Revision ID: 5bc1207e7593
Revises: 055583d82811
Create Date: 2020-04-23 10:30:45.143093

"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "5bc1207e7593"
down_revision = "055583d82811"
branch_labels = None
depends_on = None


def upgrade():
    convert_enum_to_non_native("system", "status", "ACTIVE")
    convert_enum_to_non_native("feed", "built_in_parser")
    convert_enum_to_non_native("service_map_group", "source", "SCHEDULE")
    convert_enum_to_non_native("feed_update", "update_type", "REGULAR")
    convert_enum_to_non_native("feed_update", "status")
    convert_enum_to_non_native("alert", "cause")
    convert_enum_to_non_native("alert", "effect")
    convert_enum_to_non_native("route", "type")
    convert_enum_to_non_native("trip", "current_status")

    old_enum_names = [
        "systemstatus",
        "builtinparser",
        "servicemapsource",
        "update_type",
        "status",
        "explanation",
        "cause",
        "effect",
        "route_type",
        "tripstatus",
    ]
    for enum_name in old_enum_names:
        sa.Enum(name=enum_name).drop(op.get_bind(), checkfirst=True)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###


def convert_enum_to_non_native(table_name, column_name, default=None):
    temp_column_name = column_name + "_temp"

    # Move old column to temporary new name
    op.alter_column(table_name, column_name, new_column_name=temp_column_name)

    # Create new column with old columns name
    op.add_column(
        table_name, sa.Column(column_name, sa.String(), nullable=True),
    )

    # If there is a default set, populate all fields with the default
    if default is not None:
        op.get_bind().execute(f"update {table_name} set {column_name} = '{default}'")
        op.alter_column(table_name, column_name, nullable=False)

    # Migrate the data over
    op.get_bind().execute(f"update {table_name} set {column_name} = {temp_column_name}")

    # Drop old column
    op.drop_column(table_name, temp_column_name)
