"""convert_dashboard_sections_to_views

Revision: 0198
Revision ID: 291bfbf7ca71
Revises: 3b5a33bad9e7
Create Date: 2020-10-15 09:53:02.593860

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


# revision identifiers, used by Alembic.
revision = '291bfbf7ca71'
down_revision = '3b5a33bad9e7'
branch_labels = None
depends_on = None

views = sa.Table(
    'views',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('created_at', sa.DateTime),
    sa.Column('user_id', sa.Integer),
    sa.Column('name', sa.String),
    sa.Column('filter', sa.String),
    sa.Column('filter_scopes', postgresql.JSONB),
    sa.Column('mode', sa.String),
    sa.Column('position', sa.Integer)
)


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

    stmt = sa.text("""
        select id, dashboard_sections, (select coalesce(max(position), 0) from views where user_id=id) from users where
            not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Overdue cards assigned to me")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Due cards assigned to me")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Assigned to me")')

            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Cartes en retard qui me sont assignées")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Cartes arrivant à échéance qui me sont assignées")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Assigné à moi")')

            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Überfällige Karten, die mir zugewiesen wurden")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Due cards assigned to me")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Mir zugewiesen")')

            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Tarjetas vencidas asignadas a mí")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Tarjetas por completar asignadas a mí")')
            and not (dashboard_sections::jsonb @? '$[*].title ? (@ == "Asignadas a mí")')
    """)

    for row in conn.execute(stmt):
        for i, section in enumerate(row[1]):
            conn.execute(views.insert().values(
                user_id=row[0],
                created_at=datetime.datetime.utcnow(),
                name=section['title'],
                filter=section['filter'],
                filter_scopes=[['user', row[0]]],
                mode='list',
                position=row[2] + i + 1
            ))


def downgrade():
    pass
