"""Remove all_mediaserver view

Revision ID: 742a7e247e0c
Revises: b57eb2e42524

"""

# revision identifiers, used by Alembic.
revision = '742a7e247e0c'
down_revision = 'b57eb2e42524'

import sqlalchemy as sa
from sqlalchemy import sql

from alembic import op

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

netiface_table = sql.table('netiface',
                           sql.column('networktype'),
                           sql.column('address'))

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

remove_mds_main = (mediaserver_table
                   .delete()
                   .where(mediaserver_table.c.name == 'default'))


def _insert_global_mds():
    insert_global_mds = (mediaserver_table
                         .insert()
                         .values(name='all_mds',
                                 display_name='All MDS',
                                 voip_ip=None,
                                 read_only=True))

    op.execute(remove_global_mds)
    op.execute(insert_global_mds)


def _insert_mds_main():
    address_column = (netiface_table.c.address,)

    get_mds_main_voip_ip = (sql.select(address_column)
                            .where(netiface_table.c.networktype == 'voip')
                            .limit(1))

    insert_mds_main = (mediaserver_table
                       .insert()
                       .values(name='default',
                               display_name='MDS Main',
                               voip_ip=get_mds_main_voip_ip,
                               read_only=True))

    op.execute(remove_mds_main)
    op.execute(insert_mds_main)


def upgrade():
    op.add_column('mediaserver',
                  sa.Column('read_only', sa.Boolean, nullable=False, server_default='False'))

    op.alter_column('mediaserver', 'voip_ip', nullable=True)

    op.execute('DROP VIEW all_mediaserver')

    _insert_global_mds()
    _insert_mds_main()


def downgrade():
    op.execute(remove_global_mds)
    op.execute(remove_mds_main)

    op.drop_column('mediaserver', 'read_only')

    op.execute("""
      CREATE OR REPLACE VIEW all_mediaserver AS
        (SELECT 0 as id, 'default' as name, 'MDS Main' as display_name, netiface.address as voip_ip, true as read_only
        FROM netiface where netiface.networktype='voip' LIMIT 1)
      UNION ALL
        (SELECT id, name, display_name, voip_ip, false as read_only
        FROM mediaserver);
    """)
