##
# Copyright (c) 2021 Xilinx, Inc.
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
# associated documentation files (the "Software"), to deal in the Software without restriction, including 
# without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
# copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to 
# the following conditions: 
# 
# The above copyright notice and this permission notice shall be included in all copies or substantial 
# portions of the Software. 
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 
# 
##
from pymongo import MongoClient
from api import settings
mongoClient = MongoClient(settings.MONGO_URI)
db = mongoClient.xregv.usercollection
def get_userdetails(uniquekey):
    global db
    return list(db.find({"uniqueid": uniquekey,"status":"A"},{"_id":0}))
    
def required_login(uniquekey):
    global db
    try:
        cursor = list(db.find({"uniqueid": uniquekey,"status":"A"}))
        if len(cursor):
            return True
        else:
            return False
    except:
        return False

def add_user(uniquekey,user):
    global db
    try:
        db.update_many({"uniqueid":uniquekey}, {"$set": user},upsert=True)
        return True
    except:
        return False

def get_user(*args):
    global db
    try:
        count = 0
        projectobj = {}
        uniquekey = ""
        for arg in args:
            if not count:
                uniquekey = arg
            else:
                projectobj[arg] = 1
            count =+1
        projectobj["_id"] = 0
        user = list(db.find({"uniqueid":uniquekey},projectobj))
        return user[0]
    except Exception as e:
        print("error--->>", str(e))
        return False

def set_user(uniquekey,setobj):
    print("function call")
    print("---------",uniquekey)
    for key in setobj:
        print(key)
    global db
    try:
        projectobj = {}
        for key in setobj:
            projectobj[key] = setobj[key]
        print("setobj------->>",projectobj)

        db.update_many({"uniqueid":uniquekey},{"$set": projectobj})
        return True
    except:
        return False

def del_user(uniquekey):
    global db
    try:
        db.update_many({"uniqueid": uniquekey},  {"$set": {"connectionstatus": 0, "status": "I"}})
        return True
    except:
        return False
