"""
Add ability for build triggers to be disabled.

Revision ID: 61cadbacb9fc
Revises: b4c2d45bc132
Create Date: 2017-10-18 12:07:26.190901
"""

# revision identifiers, used by Alembic.
revision = "61cadbacb9fc"
down_revision = "b4c2d45bc132"

import sqlalchemy as sa
from sqlalchemy.dialects import mysql


def upgrade(op, tables, tester):
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "disablereason",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("name", sa.String(length=255), nullable=False),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_disablereason")),
    )
    op.create_index("disablereason_name", "disablereason", ["name"], unique=True)

    op.bulk_insert(
        tables.disablereason,
        [
            {"id": 1, "name": "user_toggled"},
        ],
    )

    op.bulk_insert(
        tables.logentrykind,
        [
            {"name": "toggle_repo_trigger"},
        ],
    )

    op.add_column(
        "repositorybuildtrigger", sa.Column("disabled_reason_id", sa.Integer(), nullable=True)
    )
    op.add_column(
        "repositorybuildtrigger",
        sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.sql.expression.true()),
    )
    op.create_index(
        "repositorybuildtrigger_disabled_reason_id",
        "repositorybuildtrigger",
        ["disabled_reason_id"],
        unique=False,
    )
    op.create_foreign_key(
        op.f("fk_repositorybuildtrigger_disabled_reason_id_disablereason"),
        "repositorybuildtrigger",
        "disablereason",
        ["disabled_reason_id"],
        ["id"],
    )
    # ### end Alembic commands ###

    # ### population of test data ### #
    tester.populate_column(
        "repositorybuildtrigger", "disabled_reason_id", tester.TestDataType.Foreign("disablereason")
    )
    tester.populate_column("repositorybuildtrigger", "enabled", tester.TestDataType.Boolean)
    # ### end population of test data ### #


def downgrade(op, tables, tester):
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("fk_repositorybuildtrigger_disabled_reason_id_disablereason"),
        "repositorybuildtrigger",
        type_="foreignkey",
    )
    op.drop_index("repositorybuildtrigger_disabled_reason_id", table_name="repositorybuildtrigger")
    op.drop_column("repositorybuildtrigger", "enabled")
    op.drop_column("repositorybuildtrigger", "disabled_reason_id")
    op.drop_table("disablereason")
    # ### end Alembic commands ###

    op.execute(
        tables.logentrykind.delete().where(
            tables.logentrykind.c.name == op.inline_literal("toggle_repo_trigger")
        )
    )
