"""models refactor

Revision: 0034
Revision ID: 2a46d7b96e63
Revises: 166735e0e8f6
Create Date: 2015-11-19 13:42:02.468777

"""

# revision identifiers, used by Alembic.
revision = '2a46d7b96e63'
down_revision = '166735e0e8f6'
branch_labels = None
depends_on = None

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

def upgrade():
    op.add_column('card_models', sa.Column('dynamic_extends', sa.String(), nullable=True))
    op.add_column('card_models', sa.Column('is_base', sa.String(), nullable=True))
    op.execute("UPDATE card_models SET is_base = 'org' WHERE name in ('User Base Model', 'Organization Base Model')")
    op.execute("UPDATE card_models SET is_base = 'project', listable = false WHERE name LIKE '%base model' AND available_for_all is false AND created_in_id IS NOT NULL")
    op.alter_column('card_models', 'available_for_all', new_column_name='auto_enabled_on_new_projects')
    op.add_column('cards', sa.Column('base_card_model_id', sa.Integer(), nullable=True))
    op.create_foreign_key('cards_base_card_model_id', 'cards', 'card_models', ['base_card_model_id'], ['id'], ondelete='SET NULL')
    op.execute("UPDATE cards SET base_card_model_id = model_id WHERE parent_id IS NULL")


def downgrade():
    op.drop_constraint('cards_base_card_model_id', 'cards', type_='foreignkey')
    op.drop_column('cards', 'base_card_model_id')
    op.alter_column('card_models', 'auto_enabled_on_new_projects', new_column_name='available_for_all')
    op.drop_column('card_models', 'is_base')
    op.drop_column('card_models', 'dynamic_extends')
