"""Move scores out of DB data blobs and into column.

Revision ID: ee447dd6bfa8
Revises: 717a525b2193
Create Date: 2017-03-06 20:03:25.983637

"""
import json
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text

# revision identifiers, used by Alembic.
revision = 'ee447dd6bfa8'
down_revision = '717a525b2193'
branch_labels = None
depends_on = None


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

    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('score', sa.Column('points', sa.Integer(), nullable=True))
    op.add_column('score_history', sa.Column('points', sa.Integer(), nullable=True))
    # ### end Alembic commands ###

    # Migrate scores
    sql = 'SELECT userid, musicid, data FROM score'
    results = conn.execute(text(sql), {})
    for result in results:
        data = json.loads(result['data'])
        if 'points' in data:
            points = data['points']
            del data['points']
        if 'ex_score' in data:
            points = data['ex_score']
            del data['ex_score']
        sql = 'UPDATE score SET points = :points, data = :data WHERE userid = :userid AND musicid = :musicid'
        conn.execute(
            text(sql),
            {
                'data': json.dumps(data),
                'points': points,
                'userid': result['userid'],
                'musicid': result['musicid'],
            },
        )

    # Migrate score histories
    sql = 'SELECT userid, musicid, timestamp, data FROM score_history'
    results = conn.execute(text(sql), {})
    for result in results:
        data = json.loads(result['data'])
        if 'points' in data:
            points = data['points']
            del data['points']
        if 'ex_score' in data:
            points = data['ex_score']
            del data['ex_score']
        sql = 'UPDATE score_history SET points = :points, data = :data WHERE userid = :userid AND musicid = :musicid AND timestamp = :timestamp'
        conn.execute(
            text(sql),
            {
                'data': json.dumps(data),
                'points': points,
                'userid': result['userid'],
                'musicid': result['musicid'],
                'timestamp': result['timestamp'],
            },
        )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('score_history', 'points')
    op.drop_column('score', 'points')
    # ### end Alembic commands ###
