"""card_files

Revision: 0038
Revision ID: 448178393554
Revises: 11af45c6c79e
Create Date: 2015-11-28 18:02:05.528899

"""

# revision identifiers, used by Alembic.
revision = '448178393554'
down_revision = '11af45c6c79e'
branch_labels = None
depends_on = None

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

card_attributes_table = sa.Table(
    'card_attributes',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('card_id', sa.Integer),
    sa.Column('name', sa.String),
    sa.Column('type_name', sa.String),
    sa.Column('value', postgresql.JSONB)
)

def upgrade():
    card_files = op.create_table('card_files',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('created_by_id', sa.Integer(), nullable=True),
        sa.Column('created_at', sa.DateTime(), nullable=True),
        sa.Column('name', sa.String(), nullable=True),
        sa.Column('filename', sa.String(), nullable=True),
        sa.Column('mimetype', sa.String(), nullable=True),
        sa.Column('size', sa.Integer(), nullable=True),
        sa.Column('is_external', sa.Boolean(), nullable=True),
        sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ondelete='SET NULL'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_card_files_created_at'), 'card_files', ['created_at'], unique=False)

    cards_card_files = op.create_table('cards_card_files',
        sa.Column('file_id', sa.Integer(), nullable=True),
        sa.Column('card_id', sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(['card_id'], ['cards.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['file_id'], ['card_files.id'], ondelete='CASCADE')
    )

    conn = op.get_bind()
    for attr in conn.execute(card_attributes_table.select().where(card_attributes_table.c.type_name == 'files')):
        if not attr.value:
            continue
        files = []
        for f in attr.value:
            r = conn.execute(card_files.insert().values(
                name=f['name'],
                mimetype=f.get('mimetype'),
                filename=f.get('filename', f.get('s3filename', f.get('url'))),
                is_external='url' not in f
            ))
            files.append(r.inserted_primary_key[0])
        conn.execute(card_attributes_table.update()
            .where(card_attributes_table.c.id==attr.id).values(value=files))
        if files:
            op.bulk_insert(cards_card_files,
                [{"card_id":  attr.card_id, "file_id": id} for id in files])



def downgrade():
    op.drop_table('cards_card_files')
    op.drop_index(op.f('ix_card_files_created_at'), table_name='card_files')
    op.drop_table('card_files')