from ..Utilities.util import *
from ..Filters.supportMethods import *


def setup_logger():
    logger = logging.getLogger('my_logger')
    logger.setLevel(logging.DEBUG)

    # create rotating file handler
    handler = RotatingFileHandler('opcentertest.log', maxBytes=1024*1024, backupCount=5)
    handler.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    # add handler to logger
    logger.addHandler(handler)

    return logger


my_logger = setup_logger()

# mongo_url = "mongodb+srv://poornakashi:poorna1999@opcenter.eait1yd.mongodb.net/?retryWrites=true&w=majority"

# mongo_url="mongodb+srv://poorna:poorna@cluster0.u0uqpgf.mongodb.net/?retryWrites=true&w=majority"
mongo_url = 'mongodb://neil:parablu@127.0.0.1:27017'
client = MongoClient(mongo_url)



db = client.get_database('Opcenter')
dbs = client.get_database('MachinesDB')
session_dbssss = client.get_database('session_db')


#This for Authentication Users Information
auth = db.UsersData
#This for the Dashboard Data
usersTotal = dbs.usersTotal
colors = dbs.colors_set
CloudName = dbs.CloudName
LicenceData = dbs.LicenceData
AgentData = dbs.AgentVersion
blkuser = dbs.BlockUsers
LicenceDataAddil = dbs.LicenceDataAddi
spoc = dbs.spoc
MuxData = dbs.MuxData
MuxDatauserList = dbs.MuxDataUsers
sessions_collection = session_dbssss.sessions
deletedUs_ers = dbs.DeletedUsersList
soft_blk_usr = dbs.SoftBlockUsersList
dataprotectionList = dbs.dataprotection
loginHistory = db.loginHistory
bkplist = db.backupPolicyList
dashboardColor = dbs.dashboardColor
uptimeRobot = dbs.uptimeRobot
machineList = dbs.documentMachines
documentsMuxCurrent = dbs.documentsMuxCurrent
opcenterNotes = db.OpcenterNotes
oneDriveMixedUsers = dbs.documentOneDriveMis
agentRequest = dbs.agentRequest



class SessionManager:
    def __init__(self, mongo_uri):
        self.client = MongoClient(mongo_uri)
        self.db = self.client["session_db"]
        self.collection = self.db["sessions"]

    def add_session(self, user_id, session_id):
        self.collection.insert_one({"user_id": user_id, "session_id": session_id})

    def get_user_sessions(self, user_id):
        return list(self.collection.find({"user_id": user_id}))

    def logout_user(self, user_id):
        print("The user id is : ")
        print(user_id)
        self.collection.delete_one({"user_id": user_id})
        print("Successfully Deleted")

    def check_user_logged_in(self, user_id, session_id):
        sessions = self.get_user_sessions(user_id)
        for session in sessions:
            if session["session_id"] != session_id:
                self.destroy_session(session["user_id"], session["session_id"])
                return True
        return False
    
    def destroy_session(self, user_id,session_id):
        self.collection.delete_one({"user_id": user_id,"session_id":session_id})
        

session_manager = SessionManager(mongo_url)

class MongoCollections:
    def __init__(self):
        self._cloudName = None
        self._fqdn = None


    @property
    def cloudName(self):
        return self._cloudName

    @cloudName.setter
    def cloudName(self,username):
        self._cloudName = cloudName

    @property
    def fqdn(self):
        return self.fqdn

    @fqdn.setter
    def fqdn(self,username):
        self.fqdn = fqdn

    def getCompleteCloudNameCollection(self):
        cloudName = CloudName.find()
        return cloudName

    def getCloudNameDetails(self,clientName):
        cloudNameDetails = CloudName.find_one({'CloudName':clientName},sort=[('_id', pymongo.DESCENDING)])
        return cloudNameDetails

    def getListCloudNameCollection(self):
        cloudName = CloudName.find({},{"CloudName":1})
        return [cloud['CloudName'] for cloud in cloudName]
    
    def getAuthCollection(self):
        authList = auth.find()
        return authList
    
    def getAuthDetailsById(self,id):
        authDetails = auth.find_one({"_id": id},sort=[('_id', pymongo.DESCENDING)])
        return authDetails

    def getUserTotalCollection(self):
        usersTotalList = usersTotal.find()
        return usersTotalList


    def getUserTotalByClient(self,client):
        usersTotalDetails = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])
        return usersTotalDetails

    def getColorStatusForCloud(self,clientName):
        colorFlag = "warning"

        dashboardColorCheck = dashboardColor.find_one({"cloudName":clientName},sort=[('_id', pymongo.DESCENDING)])

        if dashboardColorCheck is not None:
            color = dashboardColorCheck.get("status")


            if color is None:
                return "warning"

            if(color == "red"):
                colorFlag = "warning"
            else:
                colorFlag = "healthy"
        return colorFlag


    def getCloudMainDetails(self,clientName,filterPipeline):
        clientPrefix = "cloud_"+clientName
        print(clientPrefix)
        print("................................")
        ClouddateDataCollection = dbs[clientPrefix]
        cursor = ClouddateDataCollection.aggregate(filterPipeline)
        return cursor
        

    def getCloudMainDetailsByClient(self,clientName):
        clientPrefix = "cloud_"+clientName
        print("This is the value..........."+ clientPrefix)
        ClouddateDataCollection = dbs[clientPrefix]
        return ClouddateDataCollection


    def getCloudMainDetailsByClientFqdn(self,clientName,fqdn):
        clientPrefix = "cloud_"+clientName
        print("This is the value..........."+ clientPrefix)
        ClouddateDataCollection = dbs[clientPrefix]
        cloudDocument = ClouddateDataCollection.find_one({"System Name":fqdn},sort=[('_id', pymongo.DESCENDING)])
        return ClouddateDataCollection

    def getCloudMainDetailsByClientDocument(self,clientName):
        clientPrefix = "cloud_"+clientName
        print("This is the value..........."+ clientPrefix)
        ClouddateDataCollection = dbs[clientPrefix]
        cloudDocument = ClouddateDataCollection.find_one({"ServerType":"0.0"},sort=[('_id', pymongo.DESCENDING)])
        return cloudDocument


    def getCloudMainDetailsByClientDistinct(self,clientName):
        clientPrefix = "cloud_"+clientName
        print("This is the value..........."+ clientPrefix)
        ClouddateDataCollection = dbs[clientPrefix]
        cloudDocument = ClouddateDataCollection.distinct("System Name")
        return list(cloudDocument)


    def getColorCollectionByClient(self,client):
        colorCollection = colors.find_one({'username':client}, sort=[('_id', pymongo.DESCENDING)])
        return colorCollection


    def getDataProtectionByClient(self,client):
        dataprocListDetails = dataprotectionList.find_one({'CloudName':client}, sort=[('_id', pymongo.DESCENDING)])
        return dataprocListDetails
        
    def getAgentVersionByClient(self,client):
        AgentVersion = AgentData.find_one({'cloudName':client}, sort=[('_id', pymongo.DESCENDING)])
        return AgentVersion


    def getLicenseAdditionalByClient(self,client):
        licenceAditional = LicenceDataAddil.find_one({'cloudName':client}, sort=[('_id', pymongo.DESCENDING)])
        return licenceAditional

    def getLicenseCollectionByCloud(self,client):
        licenseCollection = LicenceData.find_one({'cloudName':client},sort=[('_id', pymongo.DESCENDING)])
        return licenseCollection

    def getBackupPolicyDataCollection(self,client):
        backupPolicyCollection = bkplist.find_one({"cloudName":client}, sort=[('_id', pymongo.DESCENDING)])
        print(backupPolicyCollection)
        return backupPolicyCollection


    def getTotalMachineList(self,client):
        return machineList.find_one({"cloudName" : client},sort=[("_id", pymongo.DESCENDING)])

    # def getColorCollectionDetailsByFqdn(client):


    def getCloudMainDetailsByFqdn(self,fqdn,clientName):
        clientPrefix = "cloud_"+clientName
        ClouddateDataCollection = dbs[clientPrefix]
        print(fqdn)
        print("The above is the fqdn................")
        cursorFinal = ClouddateDataCollection.find_one({'System Name':fqdn},sort=[("Date & Time ",-1)])
        return cursorFinal


    def getDashboardStatusByClient(self,client):
        dashboardColorCheck = dashboardColor.find_one({"cloudName":client},sort=[('_id', pymongo.DESCENDING)])
        if dashboardColorCheck is not None:
            color = dashboardColorCheck.get("status")
            if(color == "red"):
                color = "warning"
            else:
                color = "healthy"
        else:
            color = "warning"

        return color


    def getNotesByAll(self):
        OpcenterNotes = opcenterNotes.find()
        return OpcenterNotes

    def setNotesByAll(self,collection):
        opcenterNotes.insert_one(collection)

    def getNotesByAll(self):
        opcentersticky = list(opcenterNotes.find())
        return opcentersticky

    def removeNoteOpcenter(self,delete_id):
        print("......The delete id is")
        print(delete_id)
        object_id = ObjectId(delete_id)
        result = opcenterNotes.delete_one({"_id": object_id})
        print(result.deleted_count)

    def getDistictSystemNameInCloud(self,cloudName,fqdn):
        cloudSuffix = "cloud_"+cloudName
        ClouddateDataCollection = dbs[cloudSuffix]
        cursorFinal = ClouddateDataCollection.find_one({'System Name':fqdn},sort=[('_id', pymongo.DESCENDING)])
        return cursorFinal

    
    def getMuxCollectionByCloud(self,client):
        cloudSuffix = "cloud_"+client+"mux"
        myMachineMuxCollection = dbs[cloudSuffix]
        return myMachineMuxCollection


    def getMuxCollectionDetailsByBucket(self,client,odblogin):
        cloudSuffix = "cloud_"+client+"mux"
        myMachineMuxCollection = dbs[cloudSuffix]
        odbDetails = myMachineMuxCollection.find_one({'odbLoginId': odblogin},sort=[("_id", -1)])
        return odbDetails


    def getMuxBucketList(self,client):
        currentBuckets = documentsMuxCurrent.find_one({'CloudName': client},sort=[("_id", -1)])
        if currentBuckets is not None:
            currentBucketsList = currentBuckets.get("CurrentList")
        else:
            currentBucketsList = []
        return currentBucketsList


    def getMuxUsersList(self,client):
        muxUsersList = MuxDatauserList.find_one({'cloudName': client},sort=[("_id", -1)])
        try:
            muxList = muxUsersList.get("muxFileUsers")
        except Exception as e:
            print(e)
            muxList = []
        return muxList


    def getOneDriveMixedUsers(self,client):
        oneDriveMixed = oneDriveMixedUsers.find_one({"cloudName":client}, sort=[('_id', pymongo.DESCENDING)])
        if oneDriveMixed is not None:
            oneDriveMixedUsersList = oneDriveMixed.get("OneDriveMisList")
        else:
            oneDriveMixedUsersList = []
        return oneDriveMixedUsersList    

    def getDistinctOdbLoginByClient(self,client):
        print(client)
        print("The above is the value of the cloud name")
        cloudSuffix = "cloud_"+client+"mux"
        myMachineMuxCollection = dbs[cloudSuffix]
        unique_odbLoginIds = list(myMachineMuxCollection.distinct('odbLoginId'))
        return unique_odbLoginIds
    
    def getBlockedUsersListByCloud(self,client):
        blockedUsers = blkuser.find_one({'cloudName': client},sort=[("_id",pymongo.DESCENDING)])
        blockListUsersList = blockedUsers.get('BlockUsers')
        return list(filter(None, blockListUsersList))

    def getSoftBlockedUsersList(self,client):
        so_FtBloc = soft_blk_usr.find_one({'cloudName': client},sort=[("_id",pymongo.DESCENDING)])
        sof_tBLok = so_FtBloc.get("SoftBlockUsersList")
        return sof_tBLok

    def getDeletedUsersList(self,client):
        deletedUsers = deletedUs_ers.find_one({'cloudName': client},sort=[("_id",pymongo.DESCENDING)])
        Del_usz = deletedUsers.get("DeletedUsers")
        return Del_usz

    def setMacAgentRequest(self,data_set):
        inserted_record = agentRequest.insert_one(data_set)
        if inserted_record.inserted_id:
            return inserted_record.inserted_id
        else:
            return None

    def getAgentDetails(self,agentId):
        object_id = ObjectId(agentId)
        agentRequestCollection = agentRequest.find_one({'_id': object_id},sort=[("_id",pymongo.DESCENDING)])
        return agentRequestCollection


    def getApprovedDetails(self):
        agentApprovedCollection = list(agentRequest.find({'agentstatus': "Approved"}))
        response_data = json_util.dumps(agentApprovedCollection)
        return response_data


    def updateAgentDetails(self,agentId,approvedBy,current_timestamp_millis):
        object_id = ObjectId(agentId)
        filter = {"_id": object_id}
        update = {
            "$set": {
                "agentstatus": "Approved",
                "approvedBy": approvedBy,
                "approval":True,
                "approvedOn" : current_timestamp_millis
            }
        }
        result = agentRequest.update_one(filter, update)
        if result.modified_count == 1:
            return True
        else:
            return False


    def updateAgentCreatedDetails(self,agentId,createdBy,current_timetamp_millis,agentLinks):
        object_id = ObjectId(agentId)
        filter = {"_id": object_id}
        update = {
            "$set": {
                "agentstatus": "Agent Created",
                "agentcreatedTime": current_timetamp_millis,
                "agentcreatedBy":createdBy,
                "agentLinks":agentLinks
            }
        }

        result = agentRequest.update_one(filter, update)
        if result.modified_count == 1:
            return True
        else:
            return False

        
    def getSuperAdminList(self):
        usersList = []
        query = {"accessType": "superadmin"}
        superadmin_users = auth.find(query)
        for user in superadmin_users:
            usersList.append(user['email'])
        return usersList


    def getAllAgentRequest(self):
        agentList = []
        agentRequestList = agentRequest.find()
        for agents in agentRequestList:
            agentList.append(agents)
        return agentList
    


MongoCollectionInstance = MongoCollections()
CloudNameCollection = list(MongoCollectionInstance.getListCloudNameCollection())
AuthCollection = MongoCollectionInstance.getAuthCollection()
UserTotalCollection = MongoCollectionInstance.getUserTotalCollection()
