"""log_type_to_org

Revision: 0090
Revision ID: 4be9e24293aa
Revises: 6dac66a4490
Create Date: 2017-03-17 17:48:06.314584

"""

# revision identifiers, used by Alembic.
revision = '4be9e24293aa'
down_revision = '6dac66a4490'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.add_column('card_log_types', sa.Column('owner_id', sa.Integer(), nullable=True))
    op.create_foreign_key(None, 'card_log_types', 'organizations', ['owner_id'], ['id'], ondelete='CASCADE')
    op.create_index(op.f('ix_card_log_types_owner_id'), 'card_log_types', ['owner_id'], unique=False)

    op.add_column('card_log_types', sa.Column('is_project_specific', sa.Boolean(), nullable=True))

    op.create_table(
        'project_enabled_log_types',
        sa.Column('log_type_id', sa.Integer(), nullable=False),
        sa.Column('project_id', sa.Integer(), nullable=False),
        sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['log_type_id'], ['card_log_types.id'], ondelete='CASCADE')
    )
    op.create_index(op.f('ix_project_enabled_log_types_log_type_id'), 'project_enabled_log_types', ['log_type_id'], unique=False)
    op.create_index(op.f('ix_project_enabled_log_types_project_id'), 'project_enabled_log_types', ['project_id'], unique=False)

    op.execute("INSERT INTO project_enabled_log_types (project_id, log_type_id) SELECT project_id, id FROM card_log_types")
    op.execute("UPDATE card_log_types SET is_project_specific = true")

    op.drop_column('card_log_types', 'project_id')


def downgrade():
    op.drop_column('card_log_types', 'is_project_specific')
    op.drop_column('card_log_types', 'owner_id')
