"""migrate_card_show_on_tile

Revision: 0173
Revision ID: 10e15642295c
Revises: 34c57eb46c8a
Create Date: 2019-09-04 14:41:59.072829

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


# revision identifiers, used by Alembic.
revision = '10e15642295c'
down_revision = '34c57eb46c8a'
branch_labels = None
depends_on = None


views = sa.Table(
    'views',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('mode_options', postgresql.JSONB)
)


def upgrade():
    conn = op.get_bind()
    views_options = {}
    special_attrs = ['__ref__', '__comments__', '__children__', '__cover__']

    res = conn.execute(sa.text("""
        SELECT v.id, v.mode_options
        FROM views v
        WHERE v.mode = 'kanban'
    """))
    for r in res:
        mode_options = r[1] or {}
        mode_options.update({'visible_attributes': list(special_attrs)})
        views_options[r[0]] = mode_options

    if not views_options:
        return

    queries = [
        """
            SELECT v.id, array_agg(a.name)
            FROM views v
                JOIN projects p ON v.project_id = p.id
                JOIN project_enabled_models pem ON pem.project_id = p.id
                JOIN card_models cm ON cm.id = pem.model_id,
                attributes a
            WHERE v.mode = 'kanban' AND a.show_on_tile
            AND a.group_id = cm.attribute_group_id
            GROUP BY v.id
        """,
        """
            SELECT v.id, array_agg(a.name)
            FROM views v
                JOIN projects p ON v.project_id = p.id
                JOIN organizations o ON o.id = p.owner_id,
                attributes a
            WHERE v.mode = 'kanban' AND a.show_on_tile
            AND (
                a.group_id = p.attribute_group_id OR
                p.use_org_attributes AND a.group_id = o.attribute_group_id
            )
            GROUP BY v.id
        """,
        """
            SELECT v.id, array_agg(cgt.name)
            FROM views v
                JOIN projects p ON v.project_id = p.id
                JOIN project_enabled_group_types pegt ON pegt.project_id = p.id
                JOIN card_group_types cgt ON cgt.id = pegt.group_type_id
            WHERE v.mode = 'kanban' AND cgt.display_on_card IS NOT NULL
            GROUP BY v.id
        """
    ]
    for q in queries:
        res = conn.execute(sa.text(q))
        for r in res:
            views_options[r[0]]['visible_attributes'].extend(r[1])

    view_params = [{'view_id': view_id, 'mode_options': mode_options} for (view_id, mode_options) in views_options.items()]

    conn.execute(views.update().where(views.c.id==sa.bindparam('view_id')).values(
        mode_options=sa.bindparam('mode_options')), view_params)


def downgrade():
    pass
