"""remove_all_mediaserver_entry

Revision ID: a8ced70936d4
Revises: a7f322263182

"""

# revision identifiers, used by Alembic.
revision = 'a8ced70936d4'
down_revision = 'a7f322263182'

from alembic import op
from sqlalchemy import sql
import sqlalchemy as sa

mediaserver_table = sql.table('mediaserver',
                              sql.column('id'),
                              sql.column('name'))

trunkfeatures_table = sql.table('trunkfeatures',
                                sql.column('mediaserverid'))

mediaserver_id_column = (mediaserver_table.c.id,)

all_mds_id = (sql.select(mediaserver_id_column)
              .where(mediaserver_table.c.name == 'all_mds')
              .limit(1))

mds_main_id = (sql.select(mediaserver_id_column)
               .where(mediaserver_table.c.name == 'default')
               .limit(1))

def upgrade():
    update_sip_trunk_query = (trunkfeatures_table
                        .update()
                        .values(mediaserverid=mds_main_id)
                        .where(trunkfeatures_table.c.mediaserverid == all_mds_id))

    op.execute(update_sip_trunk_query)

    delete_query = (mediaserver_table
                    .delete()
                    .where(mediaserver_table.c.name == 'all_mds'))

    op.execute(delete_query)


def downgrade():
    all_mds_query = (mediaserver_table
                     .insert()
                     .values(id=all_mds_id,
                             name='all_mds',
                             display_name='All MDS',
                             read_only=True))

    op.execute(all_mds_query)

    reset_sip_trunk_query = (trunkfeatures_table
                             .update()
                             .values(mediaserverid=all_mds_id)
                             .where(trunkfeatures_table.c.mediaserverid == mds_main_id))

    op.execute(reset_sip_trunk_query)
