"""enabled_group_types

Revision: 0035
Revision ID: 30849ae581ab
Revises: 166735e0e8f6
Create Date: 2015-11-22 21:11:04.776843

"""

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

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

def upgrade():
    op.create_table('card_enabled_group_types',
        sa.Column('group_type_id', sa.Integer(), nullable=True),
        sa.Column('card_id', sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(['card_id'], ['cards.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['group_type_id'], ['card_group_types.id'], ondelete='CASCADE')
    )

    op.add_column('card_group_types', sa.Column('auto_enabled_on_new_projects', sa.Boolean(), nullable=True))
    op.add_column('card_group_types', sa.Column('is_project_specific', sa.Boolean(), nullable=True))
    
    op.add_column('cards', sa.Column('default_card_group_type_id', sa.Integer(), nullable=True))
    op.create_foreign_key(None, 'cards', 'card_group_types', ['default_card_group_type_id'], ['id'], ondelete='SET NULL')

    op.execute("UPDATE card_group_types SET is_project_specific = false, auto_enabled_on_new_projects = true")
    op.execute("""INSERT INTO card_enabled_group_types (group_type_id, card_id)
        SELECT cgt.id, c.id FROM card_group_types cgt JOIN organizations o ON o.id = cgt.owner_id
            JOIN cards c ON c.owner_id = o.id WHERE c.parent_id is null""")
    op.execute("""UPDATE cards SET default_card_group_type_id = o.default_card_group_type_id
        FROM organizations o WHERE o.id = cards.owner_id AND cards.parent_id IS NULL""")


def downgrade():
    op.drop_table('card_enabled_group_types')
    op.drop_column('cards', 'default_card_group_type_id')
    op.drop_column('card_group_types', 'is_project_specific')
    op.drop_column('card_group_types', 'auto_enabled_on_new_projects')