"""Create barcodes table.

Revision ID: 325de501b4d5
Revises: 972dcd13ed21
Create Date: 2019-03-20 11:21:50.049000

"""
import logging

from alembic import op
import sqlalchemy as sa

logger = logging.getLogger(__name__)

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

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


def upgrade():
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    tables = set(inspector.get_table_names())
    if 'barcodes' in tables:
        logger.info("Table 'barcodes' already exists. Skipping its migration...")
        return

    op.create_table(
        'barcodes',
        sa.Column('key', sa.Integer(), nullable=False),
        sa.Column('menu_item_id', sa.String(length=64), nullable=True),
        sa.Column('price_level_key', sa.Integer(), nullable=True),
        sa.Column('id', sa.String(length=64), nullable=False),
        sa.Column('code', sa.String(length=128), nullable=False),
        sa.ForeignKeyConstraint(
            ['menu_item_id'],
            ['menu_items.id'],
            name='fk_barcodes_menu_item',
            onupdate='cascade',
            ondelete='cascade'
        ),
        sa.ForeignKeyConstraint(
            ['price_level_key'],
            ['price_levels.key'],
            name='fk_barcodes_price_level',
            onupdate='cascade',
            ondelete='cascade'
        ),
        sa.PrimaryKeyConstraint('key')
    )

    with op.batch_alter_table('barcodes', schema=None) as batch_op:
        batch_op.create_index('idx_barcodes_menu_item_id', ['menu_item_id'], unique=False)

    with op.batch_alter_table('barcodes', schema=None) as batch_op:
        batch_op.create_index('idx_barcodes_price_level', ['price_level_key'], unique=False)


def downgrade():
    op.drop_table('barcodes')

