"""group_type_attribute

Revision: 0067
Revision ID: 31f84a385d20
Revises: 16627338400e
Create Date: 2016-07-21 20:44:49.279036

"""

# revision identifiers, used by Alembic.
revision = '31f84a385d20'
down_revision = '16627338400e'
branch_labels = None
depends_on = None

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

organizations = sa.Table(
    'organizations',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('default_card_model_id', sa.Integer),
)

attribute_groups = sa.Table(
    'attribute_groups',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('owner_id', sa.Integer)
)

attributes = sa.Table(
    'attributes',
    sa.MetaData(),
    sa.Column('id', sa.Integer()),
    sa.Column('card_model_id', sa.Integer()),
    sa.Column('name', sa.String()),
    sa.Column('type_name', sa.String()),
    sa.Column('options', sa.PickleType()),
    sa.Column('group_id', sa.Integer())
)

card_attributes = sa.Table(
    'card_attributes',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('attribute_id', sa.Integer)
)

group_types = sa.Table(
    'card_group_types',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('owner_id', sa.Integer),
    sa.Column('name', sa.String()),
    sa.Column('attribute_id', sa.Integer)
)

card_enabled_group_types = sa.Table(
    'card_enabled_group_types',
    sa.MetaData(),
    sa.Column('group_type_id', sa.Integer()),
    sa.Column('card_id', sa.Integer())
)

card_models = sa.Table(
    'card_models',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('owner_id', sa.Integer),
    sa.Column('is_base', sa.String),
    sa.Column('created_in_id', sa.Integer),
    sa.Column('is_project_specific', sa.String),
    sa.Column('attribute_group_id', sa.Integer),
    sa.Column('extends_id', sa.Integer),
    sa.Column('dynamic_extends', sa.String)
)


def upgrade():
    op.add_column('card_group_types', sa.Column('attribute_id', sa.Integer(), nullable=True))
    op.create_index(op.f('ix_card_group_types_attribute_id'), 'card_group_types', ['attribute_id'], unique=False)

    conn = op.get_bind()
    updates = []
    deletes = []

    grouptypes = {}

    q = attributes.select().where(attributes.c.type_name == 'group_type')
    for attr in conn.execute(q):
        if attr['options'].get('group_type'):
            gt = conn.execute(group_types.select().where(group_types.c.id==attr['options']['group_type'])).first()
            if gt and gt['name'] not in ('Lists', 'Milestones'):
                if gt.id not in grouptypes:
                    org_model = conn.execute(card_models.join(organizations, card_models.c.id==organizations.c.default_card_model_id).select().where(organizations.c.id==gt.owner_id)).first()
                    conn.execute(attributes.update().where(attributes.c.id == attr.id).values(
                        group_id = org_model.attribute_group_id,
                        card_model_id = org_model[0],
                        name=gt.name
                    ))
                    grouptypes[gt.id] = attr.id
                    updates.append({'gt_id': gt['id'], 'attr_id': attr['id']})
                    continue
                else:
                    conn.execute(card_attributes.update().where(card_attributes.c.attribute_id==attr.id).values(
                        attribute_id = grouptypes[gt.id]
                    ))
        deletes.append({'attr_id': attr['id']})

    if updates:
        stmt = group_types.update().where(group_types.c.id==sa.bindparam('gt_id')).values(
            attribute_id=sa.bindparam('attr_id'))
        conn.execute(stmt, updates)

    if deletes:
        stmt = attributes.delete().where(attributes.c.id == sa.bindparam('attr_id'))
        conn.execute(stmt, deletes)

    if updates:
        stmt = card_enabled_group_types.delete().where(card_enabled_group_types.c.group_type_id == sa.bindparam('gt_id'))
        conn.execute(stmt, updates)


def downgrade():
    op.drop_index(op.f('ix_card_group_types_attribute_id'), table_name='card_group_types')
    op.drop_column('card_group_types', 'attribute_id')
