"""fix_children_default_model

Revision: 0109
Revision ID: 50312a20c5ea
Revises: 7583b4a2428
Create Date: 2018-01-09 15:20:37.912624

"""

# revision identifiers, used by Alembic.
revision = '50312a20c5ea'
down_revision = '7583b4a2428'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

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

enabled_models = sa.Table(
    'project_enabled_models',
    sa.MetaData(),
    sa.Column('project_id', sa.Integer),
    sa.Column('model_id', sa.Integer)
)

models = sa.Table(
    'card_models',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('owner_id', sa.Integer),
    sa.Column('name', sa.String()),
    sa.Column('children_default_model_id', sa.Integer),
    sa.Column('is_project_specific', sa.Boolean)
)

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

    projects2 = sa.alias(projects)
    enabled_models2 = sa.alias(enabled_models)
    models2 = sa.alias(models)

    projects3 = sa.alias(projects)
    enabled_models3 = sa.alias(enabled_models)
    models3 = sa.alias(models)

    q = sa.select([projects.c.id, models.c.id, models2.c.id, models3.c.id]).where(sa.and_(models.c.children_default_model_id == models2.c.id,
                                      models.c.id == enabled_models.c.model_id,
                                      enabled_models.c.project_id == projects.c.id,
                                      models2.c.is_project_specific == True,
                                      models2.c.id == enabled_models2.c.model_id,
                                      enabled_models2.c.project_id == projects2.c.id,
                                      projects.c.id != projects2.c.id,
                                      models3.c.id == enabled_models3.c.model_id,
                                      enabled_models3.c.project_id == projects3.c.id,
                                      projects3.c.id == projects.c.id,
                                      models3.c.name == models2.c.name))

    model_ids = []
    for model in conn.execute(q):
        op.execute("UPDATE cards SET model_id = {0} WHERE project_id = {1} AND model_id = {2}".format(model[3], model[0], model[2]))
        model_ids.append({'model_id':model[1], 'children_model_id':model[3]})

    if model_ids:
        conn.execute(models.update().where(models.c.id == sa.bindparam('model_id')).values(
            children_default_model_id=sa.bindparam('children_model_id')), model_ids)

def downgrade():
    pass
