from databaseConn import *
from databaseConn.mysqlOperation import mysqlInfo

def mongo_universal(namespace):
    mysql_universal="mongodb://{name}:{pwd}@{host}:{port}"
    mysql_info=mysqlInfo(namespace,dbtype='mongodb')
    #print(mysql_info)
    temp=mysql_universal.format(**mysql_info)
    print("mongodb连接信息:",temp)
    return temp

def personmongoClient(namespace,db="app_vcc2"):
    '''
    :param namespace:
    :param db:
    :return: 自动连接该db
    '''
    #mongo_info=mysqlInfo(namespace,dbtype='mongodb')
    temp=mongo_universal(namespace)
    #temp_db=eval("MongoClient(temp)")# .format(db=db))
    temp_db=eval("MongoClient(temp).{db}".format(db=db))
    try:
        #if temp_db.authenticate(mongo_info.get('name'),mongo_info.get('pwd')):
        return temp_db
    except:
        print('moongo连接失败',type(temp_db))
        traceback.print_exc(2)

def tableSearch(namespace,tablename,**kwargs):
    '''
    :param namespace: 测试环境的namesapce
    :param tablename: 表名
    :param kwargs: 需要包括库名和查询规则，默认是list处理。
    eg：{"db":"app_vcc2","query":[{"event":"loginSuccess"#,"userId":"70549608"},{"_id":1}]}
    :return: 返回find结果
    '''
    temp=''
    db=personmongoClient(namespace,kwargs.get('db'))
    tables=[i['name'] for i in db.list_collections()]
    if tablename not in tables:
        raise Exception('table[{}]不在databse[{}]中,所有的table如下:'.format(tablename,kwargs.get('db')),tables)
    #print("db结果",db,kwargs.get('query'))
    change_result="db.{tablename}.find(".format(tablename=tablename)
    for i in kwargs.get('query'):
        temp+=str(i)+','
    change_result+=temp[:-1]+")"
    print("mongo拼接结果：",change_result)
    return eval(change_result)




if __name__ == '__main__':
    # key={"db":"ocrDb","query":[{
    #    #,"userId":"70549608"
    # },{"_id":1}]}
    # temp=tableSearch('usergroup','ocrVerifyBaseInfo',**key)
    # result=[i for i in temp]
    # print(len(result))
    # for i in temp:
    #     print('===',i)
    # print(temp)
    print(personmongoClient('usergroup'))
