"""Clean group_types

Revision: 0106
Revision ID: 187c2a740494
Revises: 2272df6f8a44
Create Date: 2017-10-10 18:41:07.566598

"""

# revision identifiers, used by Alembic.
revision = '187c2a740494'
down_revision = '2272df6f8a44'
branch_labels = None
depends_on = None

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

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)
)

attributes = sa.Table(
    'attributes',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('group_id', sa.Integer)
)

card_models = sa.Table(
    'card_models',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('attribute_group_id', sa.Integer)
)

def upgrade():
    conn = op.get_bind()

    q = sa.select([group_types.c.attribute_id]).where(group_types.c.attribute_id is not None).group_by(group_types.c.attribute_id).having(sa.func.count(group_types.c.attribute_id) > 1)
    q2 = sa.select([attributes.c.group_id]).where(attributes.c.id.in_(q))
    q3 = card_models.select().where(card_models.c.attribute_group_id.in_(q2))
    models = ""
    for model in conn.execute(q3):
        if models != '':
            models += ','
        models += '%s' % model[0]

    q2 = group_types.select().where(group_types.c.attribute_id.in_(q)).order_by(group_types.c.attribute_id, group_types.c.id)
    orig_gt = None
    for gt in conn.execute(q2):
        if orig_gt is None or orig_gt[3] != gt[3]:
            orig_gt = gt
            continue
        op.execute('UPDATE card_groups SET group_type_id =%d, cache_id = uuid_generate_v4() WHERE group_type_id = %d' % (orig_gt[0], gt[0]))
        op.execute('DELETE FROM card_group_types WHERE id = %d' % gt[0])

    if models != "":
        op.execute('UPDATE card_models SET cache_id = uuid_generate_v4() WHERE id IN (%s)' % models)

def downgrade():
    pass
