"""

Code for testing ovs connection to OVN north DB
The north DB was configured with:
    ovn-nbctl set-connection ptcp:6641
"""

import time
import six

import ovs.db.idl


OVS_CONNECTION='tcp:127.0.0.1:6641'

OVN_NB_OVSSCHEMA_FILE = '/usr/share/openvswitch/ovn-nb.ovsschema'
NETWORK_TABLE_COLUMNS = ['name', 'ports', 'other_config', 'external_ids']
NETWORK_TABLE = 'Logical_Switch'


def get_schema_helper():
    schema_helper = ovs.db.idl.SchemaHelper(OVN_NB_OVSSCHEMA_FILE)
    schema_helper.register_columns(NETWORK_TABLE, NETWORK_TABLE_COLUMNS)
    return schema_helper

def get_networks(ovsdb_connection):
    rows = ovsdb_connection.tables['Logical_Switch'].rows
    for row in six.itervalues(rows):
        print('ROW: uuid:' + str(row.uuid) + '  name:' + str(row.name))

def connect():
    schema_helper=get_schema_helper()
    ovsdb_connection = ovs.db.idl.Idl(OVS_CONNECTION, schema_helper)

    i=1
    start = time.time()
    while (time.time() - start) < 30:
        ovsdb_connection.run()
        if ovsdb_connection.has_ever_connected():
            print('CONNECTED!')
            return ovsdb_connection
        print('connecting  ' + str(i) )
        i=i+1
        time.sleep(0.01)

    raise Exception('Failed to connect')

try:
    ovsdb_connection = connect()
    get_networks(ovsdb_connection)
except Exception as e:
    print('Exception' + str(e))