"""menu category types

Revision ID: bdbcca2c4ba0d5
Revises: 325de501b4d5
Create Date: 2019-03-17 09:45:22.544000

"""
import logging

from alembic import op, context
import sqlalchemy as sa

logger = logging.getLogger(__name__)

# revision identifiers, used by Alembic.
revision = 'bdbcca2c4ba0d5'
down_revision = '325de501b4d5'
branch_labels = None
depends_on = None

# TODO: Set the first_agent_version correctly before merging this revision
first_agent_version = '19.3.21'


def upgrade():
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    tables = set(inspector.get_table_names())

    try:
        connection.execute("pragma foreign_keys = 0")

        if 'menu_category_types' in tables:
            logger.info("Table 'menu_category_types' already exists. Skipping its migration...")
        else:
            op.create_table(
                'menu_category_types',
                sa.Column('id', sa.String(64), primary_key=True),
                sa.Column('name', sa.String(128)),
                sa.Column('_registered_property_values', sa.BLOB()),
            )

        with op.batch_alter_table('menu_categories', schema=None) as batch_op:
            batch_op.add_column(sa.Column('menu_category_type_id', sa.String(64), nullable=True))
            batch_op.create_foreign_key(
                'fk_menu_categories_menu_category_type_id',
                'menu_category_types',
                ['menu_category_type_id'],
                ['id'],
            )
            batch_op.create_index('idx_menu_categories_menu_category_type_id', ['menu_category_type_id'], unique=False)
    finally:
        connection.execute('PRAGMA foreign_keys = "1";')



def downgrade():
    current_context = context.get_context()
    inspector = sa.inspect(current_context.connection)
    tables = set(inspector.get_table_names())

    try:
        current_context.connection.execute("pragma foreign_keys = 0")

        with op.batch_alter_table('menu_categories', schema=None) as batch_op:
            batch_op.drop_index('idx_menu_categories_menu_category_type_id')
            batch_op.drop_column('menu_category_type_id')

        if 'menu_category_types' in tables:
            op.drop_table('menu_category_types')

    finally:
        current_context.connection.execute('PRAGMA foreign_keys = "1";')
