import json


def configure_connection (instance, name = 'database', credentials = None):
    """Configures IBM Streams for a certain connection.


    Creates or updates an application configuration object containing the required properties with connection information.


    Example for creating a configuration for a Streams instance with connection details::

        from icpd_core import icpd_util
        from streamsx.rest_primitives import Instance
        import streamsx.database as db
        
        cfg = icpd_util.get_service_instance_details (name='your-streams-instance')
        cfg[context.ConfigParams.SSL_VERIFY] = False
        instance = Instance.of_service (cfg)
        app_cfg = db.configure_connection (instance, credentials = 'my_credentials_json')

    In Cloud Pak for Data you can configure a connection to Db2 with `Connecting to data sources <https://www.ibm.com/support/producthub/icpdata/docs/content/SSQNUZ_current/cpd/access/connect-data-sources.html>`_
    Example using this configured external connection with the name 'Db2-Cloud' to create an application configuration for IBM Streams::

        db_external_connection = icpd_util.get_connection('Db2-Cloud',conn_class='external')
        app_cfg = db.configure_connection (instance, credentials = db_external_connection)


    Args:
        instance(streamsx.rest_primitives.Instance): IBM Streams instance object.
        name(str): Name of the application configuration, default name is 'database'.
        credentials(str|dict): The service credentials, for example Db2 Warehouse service credentials.
    Returns:
        Name of the application configuration.
    """

    description = 'Database credentials'
    properties = {}
    if credentials is None:
        raise TypeError (credentials)
    
    if isinstance (credentials, dict):
        if 'class' in credentials:
            if credentials.get('class') == 'external': # CP4D external connection
                if 'url' in credentials:
                    db_json = {}
                    db_json['jdbcurl'] = credentials.get('url')
                    db_json['username'] = credentials.get('username')
                    db_json['password'] = credentials.get('password')
                    properties ['credentials'] = json.dumps (db_json)
                else:
                    raise TypeError(credentials)
        else:
            properties ['credentials'] = json.dumps (credentials)
    else:
        properties ['credentials'] = credentials
    
    # check if application configuration exists
    app_config = instance.get_application_configurations (name = name)
    if app_config:
        print ('update application configuration: ' + name)
        app_config[0].update (properties)
    else:
        print ('create application configuration: ' + name)
        instance.create_application_configuration (name, properties, description)
    return name