"""labels color

Revision: 0042
Revision ID: da5397402d5
Revises: 5409e2aad044
Create Date: 2015-12-09 19:58:09.950353

"""

# revision identifiers, used by Alembic.
revision = 'da5397402d5'
down_revision = '5409e2aad044'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import select
from sqlalchemy.dialects import postgresql
import pickle

cards = sa.Table(
    'cards',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('parent_id', sa.Integer),
    sa.Column('children_attributes_ctx', sa.PickleType, default=dict)
)

card_attributes = 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('card_model_attribute_id', sa.Integer)
)

def upgrade():
    conn = op.get_bind()
    q = select([card_attributes, cards.c.parent_id])\
        .where(sa.and_(cards.c.id == card_attributes.c.card_id, card_attributes.c.type_name == 'labels'))\
        .order_by(cards.c.parent_id)

    parent_id = None
    ctx = None
    for attr in conn.execute(q):
        if parent_id != attr.parent_id:
            parent_id = attr.parent_id
            if parent_id is None:
                parent_id = attr.card_id
            ctx = conn.execute(select([cards.c.children_attributes_ctx]).where(cards.c.id==parent_id)).scalar()
        key = '%s:%s' % (attr.name, attr.type_name)
        if key in ctx:
            newKey = '%i:%s' % (attr.card_model_attribute_id, attr.type_name)
            ctx[newKey] = {}
            for title, color in ctx.get(key, {}).items():
                ctx[newKey][title] = color
            del ctx[key]
            conn.execute(cards.update().where(cards.c.id==parent_id).values(children_attributes_ctx=ctx))

def downgrade():
    pass
