"""Remove builtin base model

Revision: 0075
Revision ID: 1f8b6ec9e38a
Revises: 205096351a13
Create Date: 2016-10-27 15:47:17.462243

"""

# revision identifiers, used by Alembic.
revision = '1f8b6ec9e38a'
down_revision = '205096351a13'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
import uuid

cards = sa.Table(
    'cards',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('model_id', sa.Integer),
    sa.Column('default_child_card_model_id', sa.Integer),
    sa.Column('cache_id', sa.String)
)

card_models = sa.Table(
    'card_models',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('owner_id', sa.Integer),
    sa.Column('name', sa.String)
)

def upgrade():
    conn = op.get_bind()

    builtin_base_model = conn.execute(cards.select().where(sa.and_(card_models.c.id==1, card_models.c.owner_id==None, card_models.c.name=='Built-in Base Model'))).first()
    if builtin_base_model:
        cards_ids = []
        for card in conn.execute(cards.select().where(sa.or_(cards.c.model_id==1, cards.c.default_child_card_model_id==1))):
            cards_ids.append({'card_id':card.id, 'cache_id':uuid.uuid4()})

        conn.execute(card_models.delete().where(card_models.c.id == 1))

        if cards_ids:
            conn.execute(cards.update().where(cards.c.id == sa.bindparam('card_id')).values(
                cache_id=sa.bindparam('cache_id')), cards_ids)


def downgrade():
    pass
