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 mongoClient(namespace,db="app_vcc2"):
    '''
    :param namespace:
    :param db:
    :return: 自动连接该db
    '''
    temp=mongo_universal(namespace)
    return eval("MongoClient(temp).{db}".format(db=db))

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=mongoClient(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('qa','system.version',**key)
    result=[i for i in temp]
    print(len(result))
    for i in temp:
        print('===',i)
    print(temp)