"""fix_duplicate_groups

Revision: 0115
Revision ID: 28ef45c94dfd
Revises: 4b8f6f8c1e02
Create Date: 2018-03-09 16:10:35.897709

"""

# revision identifiers, used by Alembic.
revision = '28ef45c94dfd'
down_revision = '4b8f6f8c1e02'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

groups = sa.Table(
    'card_groups',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
)


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

    q_groups = sa.text("""
        SELECT g1.id, count(gc1.card_id), g2.id, count(gc2.card_id)
        FROM card_groups g1
        JOIN card_groups g2
        ON g1.title = g2.title
        AND g1.group_type_id = g2.group_type_id
        AND g1.parent_id = g2.parent_id
        AND g1.id != g2.id
        LEFT JOIN card_groups_cards gc1
        ON gc1.group_id = g1.id
        LEFT JOIN card_groups_cards gc2
        ON gc2.group_id = g2.id
        GROUP BY g1.id, g2.id
        ORDER BY g1.id
    """)

    groups_to_delete = []
    for group in conn.execute(q_groups):
        if group[0] in groups_to_delete or group[2] in groups_to_delete:
            continue

        if group[1] == 0 and group[3] == 0 or group[1] > 0 and group[3] == 0:
            groups_to_delete.append(group[2])
        elif group[1] == 0 and group[3] > 0:
            groups_to_delete.append(group[0])

    conn.execute(groups.delete().where(groups.c.id.in_(groups_to_delete)))


def downgrade():
    pass
