########################################################################
#
# File Name: 	        Util.py
#
# Documentation:	http://docs.ftsuite.com/4ODS/Drivers/Util.py.html
#
"""
Utils for all adapters
WWW: http://4suite.org/4ODS         e-mail: support@4suite.org

Copyright (c) 1999 Fourthought, Inc, USA.   All Rights Reserved.
See  http://4suite.org/COPYRIGHT  for license and copyright information
"""
import sys,string

import string

from Ft.Ods import Exception

def SplitDbConnectString(connString):

    #ods:userName/password@hostName:port:dbName
    username = None
    passwd = None
    hostname = None
    port = -1
    dbName = None
    #or just
    #dbName

    original = connString

    if connString[:4] == 'ods:':
        connString = connString[4:]
    else:
        return (connString,hostname,port,username,passwd)

    fields = string.split(connString,'@')
    if len(fields) == 2:
        #break out username and password
        networkString = fields[1]

        #Look for password
        fields = string.split(fields[0],'/')
        if len(fields) == 2:
            #We have both
            username,passwd = fields[0],fields[1]
        elif len(fields) == 1:
            #only username
            username,passwd = fields[0],None
        else:
            raise Exception.FtodsInvalidConnectionString(connectString=original,reason="Too many /")


    elif len(fields) > 2:
        raise Exception.FtodsInvalidConnectionString(connectString=original,reason="Too many @")
    else:
        networkString = fields[0]

    fields = string.split(networkString,':')
    if len(fields) == 3:
        #All of them
        hostname = fields[0]
        if len(fields[1]) > 0:
            port = int(fields[1])
        dbName = fields[2]
    elif len(fields) == 2:
        #Host and db
        hostname = fields[0]
        dbName = fields[1]
    elif len(fields) == 1:
        #db
        dbName = fields[0]
    else:
        raise Exception.FtodsInvalidConnectionString(connectString=original,reason="Too many :")


    return (dbName,hostname,port,username,passwd)



if __name__ == '__main__':
    print SplitDbConnectString("foo")
    print SplitDbConnectString("ods:foo")
    print SplitDbConnectString("ods:www.python.org:foo")
    print SplitDbConnectString("ods:www.python.org:23:foo")
    print SplitDbConnectString("ods:molson@foo")
    print SplitDbConnectString("ods:molson@www.python.org:foo")
    print SplitDbConnectString("ods:molson@www.python.org:23:foo")
    print SplitDbConnectString("ods:molson/mpass@foo")
    print SplitDbConnectString("ods:molson/mpass@www.python.org:foo")
    print SplitDbConnectString("ods:molson/mpass@www.python.org::foo")
    print SplitDbConnectString("ods:molson/mpass@www.python.org:23:foo")


    
