"""option_ref

Revision: 0193
Revision ID: 60fef5bde116
Revises: b01140bf6710
Create Date: 2020-09-15 14:34:10.190593

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


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


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


def upgrade():
    op.execute("""
        UPDATE project_auto_actions
        SET options = jsonb_build_object('group',
            jsonb_build_object('name', options->'group',
                'group_type', jsonb_build_object('name', options->'group_type'))
        )
        WHERE action_name = 'append_to_group'
    """)

    op.execute("""
        UPDATE project_auto_actions
        SET options = jsonb_build_object('request_form', options->'form_id')
        WHERE action_name = 'create_request_on_card'
    """)

    op.execute("""
        UPDATE project_auto_actions
        SET options = jsonb_build_object(
            'email_template', options->'template_id',
            'recipient_attr', options->'recipient_attr_id'
        )
        WHERE action_name = 'send_email'
    """)

    conn = op.get_bind()
    updates = []
    for view in conn.execute(views.select().where(views.c.mode == 'report')):
        if isinstance(view['mode_options'], dict) and view['mode_options'].get('widgets'):
            for widget in view['mode_options']['widgets']:
                if widget['chart'] == 'burndown_chart':
                    _rename_key(widget, 'group_type_id', 'group_type')
                    _rename_key(widget, 'group_id', 'group')
                    _rename_key(widget, 'points_attr_id', 'points_attr')
                elif widget['chart'] in ('groups', 'cards_per_group_breakdown', 'cycle_times', 'cumulative_flow_diagram'):
                    _rename_key(widget, 'group_type_id', 'group_type')
                elif widget['chart'] in ('time_between_two_groups', 'evolution_of_time_between_two_groups'):
                    _rename_key(widget, 'from_group_id', 'from_group')
                    _rename_key(widget, 'to_group_id', 'to_group')
                elif widget['chart'] == 'evolution_nb_cards_in_group':
                    _rename_key(widget, 'group_id', 'group')
                elif widget['chart'] in ('logs_count', 'logs_number_daily', 'logs_number_sum', 'logs_number_sum_by_user'):
                    _rename_key(widget, 'log_type_id', 'log_type')
                elif widget['chart'] == 'weekly_velocity_chart':
                    _rename_key(widget, 'points_attr_id', 'points_attr')
                elif widget['chart'] == 'groups_velocity_chart':
                    _rename_key(widget, 'group_type_id', 'group_type')
                    _rename_key(widget, 'points_attr_id', 'points_attr')
                elif widget['chart'] == 'members_velocity_chart':
                    _rename_key(widget, 'members_attr_id', 'members_attr')
                    _rename_key(widget, 'group_type_id', 'group_type')
                    _rename_key(widget, 'points_attr_id', 'points_attr')
                elif widget['chart'] == 'workload':
                    _rename_key(widget, 'ponderate_attr_id', 'ponderate_attr')
            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


def _rename_key(widget, old_key, new_key):
    v = widget['options'].pop(old_key, None)
    if v:
        widget['options'][new_key] = v
