"""Add stakes table


Revision ID: 48992f94caca
Revises: f0bbcc4ae914
Create Date: 2019-10-21 05:44:51.748330

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
from models import Stakes, Table, Hand


# revision identifiers, used by Alembic.
revision = '48992f94caca'
down_revision = 'f0bbcc4ae914'
branch_labels = None
depends_on = None

Base = declarative_base()


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('stakes',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('small', sa.Integer(), nullable=False),
    sa.Column('big', sa.Integer(), nullable=False),
    sa.Column('ante', sa.Integer(), nullable=False),
    sa.Column('created_utc', sa.DateTime(), nullable=True),
    sa.CheckConstraint('big >= small'),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

    bind = op.get_bind()
    session = orm.Session(bind=bind)

    op.add_column('hands', sa.Column('stakes_id', sa.Integer(), nullable=True))
    op.create_foreign_key('hands_stakes_id_fkey', 'hands', 'stakes', ['stakes_id'], ['id'])
    op.add_column('tables', sa.Column('stakes_id', sa.Integer(), nullable=True))
    op.create_foreign_key('tables_stakes_id_fkey', 'tables', 'stakes', ['stakes_id'], ['id'])

    stakes = Stakes(small=25, big=50, ante=0)
    session.add(stakes)
    session.commit()

    op.execute("UPDATE hands SET stakes_id = {}".format(stakes.id))
    op.execute("UPDATE tables SET stakes_id = {}".format(stakes.id))

    op.alter_column('tables', 'stakes_id', nullable=False)
    op.alter_column('hands', 'stakes_id', nullable=False)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('tables_stakes_id_fkey', 'tables', type_='foreignkey')
    op.drop_column('tables', 'stakes_id')
    op.drop_constraint('hands_stakes_id_fkey', 'hands', type_='foreignkey')
    op.drop_column('hands', 'stakes_id')
    op.drop_table('stakes')
    # ### end Alembic commands ###
