"""added column showForEdit

Peek Plugin Database Migration Script

Revision ID: 0db3aedfee95
Revises: 128b23798db0
Create Date: 2022-07-14 16:33:02.361090

"""

# revision identifiers, used by Alembic.
revision = "0db3aedfee95"
down_revision = "128b23798db0"
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

__affectedTables = (
    "DispColor",
    "DispTextStyle",
    "DispLineStyle",
    "DispLayer",
    "DispLevel",
)


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    for tableName in __affectedTables:
        # add blockApiUpdate
        op.add_column(
            tableName,
            sa.Column(
                "blockApiUpdate",
                sa.Boolean(),
                nullable=True,
            ),
            schema="pl_diagram",
        )
        # set 'blockApiUpdate' to false
        op.execute(
            f"""
                UPDATE pl_diagram."{tableName}"
                SET "blockApiUpdate" = false
                WHERE "blockApiUpdate" IS NULL;
        """
        )
        # set 'blockApiUpdate' NOT NULL
        op.alter_column(
            f"{tableName}",
            "blockApiUpdate",
            nullable=False,
            schema="pl_diagram",
        )

        # add showForEdit
        op.add_column(
            tableName,
            sa.Column("showForEdit", sa.Boolean(), nullable=True),
            schema="pl_diagram",
        )

        # set defaults to true to named colours below
        if tableName == "DispColor":
            op.execute(
                """
                UPDATE pl_diagram."DispColor"
                SET "showForEdit" = (
                    lower("name") in (
                        'red',
                        'green',
                        'gold',
                        'orange',
                        'cyan',
                        'white',
                        'blue'
                     )
                )
                WHERE "showForEdit" IS NULL;
            """
            )
        else:
            # set 'showForEdit' to false
            op.execute(
                f"""
                UPDATE pl_diagram."{tableName}"
                SET "showForEdit" = false
                WHERE "showForEdit" IS NULL;
        """
            )

        # set 'showForEdit' NOT NULL
        op.alter_column(
            f"{tableName}", "showForEdit", nullable=False, schema="pl_diagram"
        )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    for tableName in __affectedTables:
        op.drop_column(f"{tableName}", "blockApiUpdate", schema="pl_diagram")
        op.drop_column(f"{tableName}", "showForEdit", schema="pl_diagram")
    # ### end Alembic commands ###
