"""global_views_options_ref

Revision: 0194
Revision ID: 7230cc1e84bc
Revises: 60fef5bde116
Create Date: 2020-09-22 11:31:48.293106

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


# revision identifiers, used by Alembic.
revision = '7230cc1e84bc'
down_revision = '60fef5bde116'
branch_labels = None
depends_on = None


views = sa.Table(
    'views',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('project_id', sa.Integer),
    sa.Column('user_id', sa.Integer),
    sa.Column('filter', sa.String),
    sa.Column('mode', sa.String),
    sa.Column('mode_options', postgresql.JSONB)
)


def upgrade():
    op.execute("""
        UPDATE views
        SET filter_scopes = jsonb_build_array(jsonb_build_array('user', user_id))
        WHERE project_id IS NULL AND mode != 'report'
    """)

    conn = op.get_bind()
    updates = []
    for view in conn.execute(views.select().where(sa.and_(views.c.mode == 'report', views.c.project_id==None))):
        if isinstance(view['mode_options'], dict) and view['mode_options'].get('widgets'):
            for widget in view['mode_options']['widgets']:
                widget['filter'] = view['filter']
                widget['filter_scopes'] = [['user', view['user_id']]]
            updates.append({'vid': view['id'], 'opts': view['mode_options']})

    if updates:
        stmt = views.update().where(views.c.id==sa.bindparam('vid')).values(
            mode_options=sa.bindparam('opts'))
        conn.execute(stmt, updates)

def downgrade():
    pass
