"""fix_cards_path

Revision: 0224
Revision ID: 58cf93323b46
Revises: 22b7db58107b
Create Date: 2021-10-29 16:43:51.119013

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


# revision identifiers, used by Alembic.
revision = '58cf93323b46'
down_revision = '22b7db58107b'
branch_labels = None
depends_on = None

cards = sa.Table(
    'cards',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('parent_id', sa.Integer),
    sa.Column('parents_ids', postgresql.ARRAY(sa.Integer)),
    sa.Column('cache_id', sa.String),
)

parents = {}

def find_parents(conn, card):
    if card.id in parents:
        return parents[card.id]

    parents_ids = []
    if len(card.parents_ids) == 1:
        parents_ids = [card.parent_id]
    else:
        cards2 = cards.alias()
        parent = conn.execute(cards2.select().where(sa.and_(cards2.c.id==cards.c.parent_id, cards.c.parent_id==card.parent_id))).first()
        parents_ids = list(find_parents(conn, parent))
        parents_ids.append(parent.id)

    parents[card.id] = parents_ids
    return parents_ids


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

    for card in conn.execute(cards.select().where(sa.and_(cards.c.parent_id != None, sa.any_(cards.c.parents_ids) == -1) == None)):
        find_parents(conn, card)

    if parents:
        infos = []
        for cid, parents_ids in parents.items():
            infos.append({'cid': cid, 'parents_ids': parents_ids, 'cache_id':uuid.uuid4()})
        conn.execute(cards.update().where(cards.c.id==sa.bindparam('cid')).values(
            parents_ids=sa.bindparam('parents_ids'), cache_id=sa.bindparam('cache_id')), infos)


def downgrade():
    pass
