"""Add columns to balances to get dynamically the strategy approach

Revision ID: b1f321f39713
Revises: 7add5d2cc147
Create Date: 2021-03-05 13:15:17.642442

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import MetaData, Table
import json


def choice_path(alternative_paths):
    import os
    alternative_paths = [i for i in alternative_paths if os.path.isfile(i)]
    if len(alternative_paths) == 0:
        raise FileExistsError('balances.json Does not exist')
    path = alternative_paths[0]
    return path


def get_module_path(module_name):
    parts = __file__.split('/')
    index = parts.index(module_name)
    module_path = '/'.join(parts[:index+1])
    return module_path


# revision identifiers, used by Alembic.
revision = 'b1f321f39713'
down_revision = '7add5d2cc147'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('balances', sa.Column('second_scale_from_database', sa.Boolean(), nullable=True))
    op.execute("UPDATE balances SET second_scale_from_database = True")
    op.alter_column('balances', 'second_scale_from_database', nullable=False)

    op.add_column('balances', sa.Column('trade_in_trend', sa.Boolean(), nullable=True))
    op.execute("UPDATE balances SET trade_in_trend = True")
    op.alter_column('balances', 'trade_in_trend', nullable=False)

    op.add_column('balances', sa.Column('stop_loss_percentage', sa.Numeric(), nullable=True))
    op.execute("UPDATE balances SET stop_loss_percentage = 0.3")
    op.alter_column('balances', 'stop_loss_percentage', nullable=False)

    op.add_column('balances', sa.Column('profit_percentage', sa.Numeric(), nullable=True))
    op.execute("UPDATE balances SET profit_percentage = 0.3")
    op.alter_column('balances', 'profit_percentage', nullable=False)
    module_path = get_module_path('broker_clients')
    alternative_paths = ['{}/data/balances.json'.format(module_path), '../data/balances.json']
    path = choice_path(alternative_paths)
    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.json')
    #balances_initial_data = json.load(f)
    #balances_names = [i['name'] for i in balances_initial_data]
    #records = session.query(Trades).filter(Trades.name.in_(balances_names))
    #if len(records.first()) > 0:
    #    records.delete(synchronize_session=False)
    #session.query(Balances).filter(Balances.name.in_(balances_names)).delete(synchronize_session='fetch')
    #session.commit()
    op.drop_column('balances', 'second_scale_from_database')
    op.drop_column('balances', 'trade_in_trend')
    op.drop_column('balances', 'stop_loss_percentage')
    op.drop_column('balances', 'profit_percentage')
    # ### end Alembic commands ###
