from alembic import op
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker

from portal.models.app_text import AppText
from portal.models.organization import Organization

"""empty message

Revision ID: 9b1bedfa916b
Revises: 441185240f62
Create Date: 2017-10-26 15:24:32.623899

"""

# revision identifiers, used by Alembic.
revision = '9b1bedfa916b'
down_revision = '441185240f62'

Session = sessionmaker()


def update_org_name(old, new):
    bind = op.get_bind()
    session = Session(bind=bind)

    session.execute("UPDATE organizations SET name='{}' "
                    "WHERE name='{}'".format(new, old))
    for at in session.query(AppText).filter(AppText.name.contains(old)):
        at.name = at.name.replace(old, new)
    session.commit()


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    update_org_name('CRV', 'TrueNTH Global Registry')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    update_org_name('TrueNTH Global Registry', 'CRV')
    # ### end Alembic commands ###

add migration for org name + apptext