"""Change trade_in_trend type

Revision ID: e84250567e04
Revises: 5a0ada3a67ed
Create Date: 2021-06-25 21:13:10.517179

"""
from alembic import op
import os
import json
from sqlalchemy import MetaData, Table


def get_module_path(module_name):
    import re
    return re.sub(module_name, '', __file__)

# revision identifiers, used by Alembic.
revision = 'e84250567e04'
down_revision = '5a0ada3a67ed'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("""
    CREATE TYPE tradeintrend AS ENUM (
    'none', 'first_upper_scale', 'second_upper_scale',
    'both_upper_scales', 'any_upper_scales', 'second_any_upper_scales');""")

    op.execute("""
    ALTER TABLE balances
        ALTER COLUMN trade_in_trend TYPE tradeintrend USING (
            CASE trade_in_trend
            WHEN TRUE  THEN 'any_upper_scales'::tradeintrend
            WHEN FALSE THEN 'none'::tradeintrend
            END);""")

    module_path = get_module_path(r'/alembic/versions.+')
    path = os.path.join(module_path, 'data/balances_v2.json')
    f = open(path)
    balances_initial_data = json.load(f)
    meta = MetaData(bind=op.get_bind())
    meta.reflect(only=('balances',))
    table = Table('balances', meta)
    op.bulk_insert(table, balances_initial_data)
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    #f = open('data/balances_v2.json')
    #balances_initial_data = json.load(f)
    #balances_names = [i['name'] for i in balances_initial_data]
    #session.query(Trades).filter(Trades.name.in_(balances_names)).delete(synchronize_session='fetch')
    #session.query(Balances).filter(Balances.name.in_(balances_names)).delete(synchronize_session='fetch')
    #session.commit()
    op.execute("""
    ALTER TABLE balances
        ALTER COLUMN trade_in_trend TYPE BOOLEAN USING (
            CASE trade_in_trend
            WHEN 'first_upper_scale' THEN TRUE
            WHEN 'second_upper_scale' THEN TRUE
            WHEN 'both_upper_scales' THEN TRUE
            WHEN 'any_upper_scales' THEN TRUE
            WHEN 'second_any_upper_scales' THEN TRUE
            WHEN 'none' THEN FALSE
            END);""")
    op.execute("DROP TYPE tradeintrend;")
    # ### end Alembic commands ###
