from datetime import datetime,timedelta
from functools import wraps
from flask import Blueprint,flash,session,redirect,url_for,render_template,request,jsonify,send_file
from Opcenter import usersTotal,colors,CloudName,dbs,MuxDatauserList,LicenceData,AgentData,LicenceDataAddil,spoc,MuxData,dbs,db,auth,bcrypt,sessions_collection
from Opcenter.apps.authentication.routes import is_logged_in,check_logged_in
from Opcenter import deletedUs_ers,soft_blk_usr,my_logger,dataprotectionList,config,bkplist,dashboardColor,uptimeRobot,machineList,documentsMuxCurrent,opcenterNotes,oldEntries
import time
from flask import send_file
from OpenSSL import SSL
from cryptography import x509
from cryptography.x509.oid import NameOID
import idna
from socket import socket
from collections import namedtuple
import pymongo
from distutils.version import LooseVersion
import pytz
from dateutil import parser
import uuid
import random

from Opcenter import config


HostInfo = namedtuple(field_names='cert hostname peername', typename='HostInfo')

admin = Blueprint('admin',__name__)


from datetime import datetime
now = datetime.now()

my_logger.info("I am in route that is inside the apps/admin")



def convert_to_ist(timestamp_str):
    # Define the time zones
    ist_tz = pytz.timezone('Asia/Kolkata')  # Indian Standard Time

    # Parse the input timestamp string
    timestamp = parser.parse(timestamp_str)

    # Check if the time zone is IST
    if timestamp.tzinfo == ist_tz:
        return timestamp_str

    # Convert to IST
    timestamp = timestamp.replace(tzinfo=pytz.utc).astimezone(ist_tz)

    # Format the timestamp back to string
    ist_timestamp_str = timestamp.strftime("%a %b %d %H:%M:%S IST %Y")
    return ist_timestamp_str


def compareDateWithDays(dateA, dateB,time):
    date_format = "%b %d %Y %H:%M"
    dateAvalue = datetime.strptime(dateA, date_format)
    dateBvalue = datetime.strptime(dateB, date_format)
    difference = dateAvalue - dateBvalue
    if difference.days >= time:
        my_logger.info("I am in this line 2639")
        ColorValue = "red"         
    else:
        my_logger.info("I am in this line 2642")
        ColorValue = "darkgreen"
    
    return ColorValue

def compareDate(date,duration):
    date = date.replace('IST', '+0530')
    date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
    formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')
    # last_update = datetime.strptime(date, "%a %b %d %H:%M:%S %Z %Y")


    my_logger.info("The value of the formated date")
    my_logger.info(formatted_date2)

    last_update = datetime.strptime(formatted_date2,"%b %d %Y %H:%M")

    current_date = datetime.now()

    difference = current_date - last_update
    if difference > timedelta(days=duration):
        my_logger.info("The time is older then the 3 days")
        return True
    else:
        my_logger.info("The time is not older then the 3 days")
        return False


def checkHealth(client):
   # my_logger.info("This is the Check Health --------------------------------------"+ client+"----------------------------------------------------")

    #asd = CloudName.find_one({'CloudName':client})
    #my_logger.info("The client name is : ")
    my_logger.info(client)

    col = colors.find_one({"username":client})

    #new.append(asd)
    my_logger.info("the value of asd is")
   # my_logger.info(asd)

    final_active = 0
        
    my_logger.info("The value of the client in line 144"+client)
        

    latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])


    if latest_active_data is not None:
        final_active = latest_active_data.get('Active_user_with_device', '').replace(",", "")
        my_logger.info("The value of the final_active is : ")
        my_logger.info(final_active)
        
    status = "green"

    col = colors.find_one({"username":client},sort=[('_id', pymongo.DESCENDING)])
        
    if col is None:
        clienrrrrrrName = findHostNameWithSystem(client)
        col = colors.find_one({"username":clienrrrrrrName},sort=[('_id', pymongo.DESCENDING)])

    if col is not None:
        scorecard = col.get('scorecardHeard')
        my_logger.info(scorecard)
        my_logger.info("The value of scorecard is ")
            
        if(scorecard!='0'):
            score_value = int(scorecard[:-2].split('(')[1])
        else:
            score_value = 0
    
        atleastOneUser = 0
        try:
            my_logger.info("-----------------------------------------------------------------------------------------------------------------------------------")
            my_logger.info(client)
            dataprocListNew = dataprotectionList.find_one({'CloudName':client}, sort=[('_id', pymongo.DESCENDING)])
            fullBackup = int(dataprocListNew.get("fullbackupCompleted").replace(",",""))
            atleastOneUser = int(dataprocListNew.get("atleastOneDevice").replace(",",""))
            my_logger.info("=======----------------------------------------------------++++++++++++++++++++++++++++++++++++++++++")
            my_logger.info(atleastOneUser)
            activeUsers = int(dataprocListNew.get("activeUsers").replace(",",""))
        
            
        except:
            fullBackup = 0
            activeUsers = "N/A"
            atleastOneUser = 0 
            
        my_logger.info("----------LINE 214--------------------------------")
        my_logger.info("Tje vakue of fullBackup is:"+str(fullBackup))
        my_logger.info("Tje vakue of atleast is:"+str(atleastOneUser))

        try:
            totalFullBackupPercentage = fullBackup * 100 / atleastOneUser
                #totalFullBackupPercentage = 86.5
        except Exception as e:
            my_logger.info(e)
            totalFullBackupPercentage = 0

        my_logger.info("===================================LINE 222")
        MuxType = col.get('MuxType')
        black202 =col.get('Black202')
        length202 = len(black202)
        black404 = col.get('black404')
        length404 = len(black404)
        MuxType = col.get('MuxType')
        validity = col.get('validity')
        device_proc = col.get('deviceProtected')

        if(device_proc!='0'):
            device_value = int(device_proc[:-2].split('(')[1])
        else:
            device_value = 0
        oneDrive = col.get("onedriveStorage")
        lengthOne = 0
        if oneDrive is None or len(oneDrive) == 0:
            oneDrive = 0
            lengthOne = 0
        else:
            lengthOne = len(oneDrive)

        my_logger.info("--------------------------------------"+status+"-------------------------------236-------------")

        if score_value is not None and score_value < config.scorecard:
            status = "red"
            
        my_logger.info("--------------------------------------"+status+"-------------------------------240-------------")


        if totalFullBackupPercentage is not None and totalFullBackupPercentage < 70:
            status = "red"

        my_logger.info("--------------------------------------"+status+"-------------------------------246-------------")


        if device_value is not None and device_value < 70:
            status = "red"


        my_logger.info("--------------------------------------"+status+"-------------------------------253-------------")

        if(length202>1):
            status = "red"


        my_logger.info("--------------------------------------"+status+"-------------------------------259-------------")

        if(length404>1):
            status = "red"


        my_logger.info("--------------------------------------"+status+"-------------------------------265-------------")

        if(lengthOne):
            status = "red"

        my_logger.info("--------------------------------------"+status+"-------------------------------270-------------")
    
    my_logger.info("The below is from the System View database")

    my_logger.info("======================================================================================================")
    
    try:
        SystemName = findHostNameWithSystem(client)
            
        my_logger.info("The value if the SystemName is "+SystemName)

        databaseName = "cloud_"+client
        

        my_logger.info("The valie of the databasename is : "+ databaseName)
        systemCollection = dbs[databaseName]

        systemView = systemCollection.find_one({'System Name':SystemName},sort=[("Date & Time ",pymongo.DESCENDING)])
        my_logger.info("The below is the document from the collection")
        my_logger.info(systemView)

        
        try:
            lastMongoBackup = systemView.get("lastMongoUpdate")
            my_logger.info("The last MongoBackup is: "+ lastMongoBackup)
            if(lastMongoBackup is not None or lastMongoBackup != "N/A" or lastMongoBackup != "0" or lastMongoBackup != 0):
                # result = compareDate(lastMongoBackup,3)

                recordedDate = systemView.get('Date & Time ')
                recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                recordedDate = recordedDate.strftime("%b %d %Y %H:%M")

                #Here I am checking if it in IST or different timezone
                lastMongoBackup = convert_to_ist(lastMongoBackup)


                date = lastMongoBackup.replace('IST', '+0530')
                date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')


                lastMongoUpdateColor = compareDateWithDays(recordedDate,formatted_date2,3)

                
                my_logger.info("The return result value is : ")
                # if result:
                #     my_logger.info("The last MongoBackup is older than 3 days")
                #     status = "red"
                # else:
                #     my_logger.info("The Last MongoBackup os new ")

                if lastMongoUpdateColor == "red":
                    status = "red"

            else:
                status = "red"

        except Exception as e:
            my_logger.info(e)
            my_logger.info("The value of exception is above")

        
        try:
            lastnightyrestart = systemView.get("lastNightlyRestart")
            if(lastnightyrestart != "-" or lastnightyrestart is not None or lastnightyrestart != "N/A"):
                
                # result = compareDate(lastMongoBackup,1)

                recordedDate = systemView.get('Date & Time ')
                recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                recordedDate = recordedDate.strftime("%b %d %Y %H:%M")


                lastnightyrestart = convert_to_ist(lastnightyrestart)
                date = lastnightyrestart.replace('IST', '+0530')
                date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')

                nightColor = compareDateWithDays(recordedDate,formatted_date2,1)


                if nightColor == "red":
                    status = "red"

                # my_logger.info("Tje return result value is : ")
                # if result:
                #     my_logger.info("The  Last Nightly Restart is older than 1 days")
                #     status = "red"
                # else:
                #     my_logger.info("The Last Nightly Restart os new ")
                    
            else:
                status = "red"
        except Exception as e:
            my_logger.info(e)
            status = "red"
            my_logger.info("The value of exception is above")


        try:
            physicalMemory = systemView.get("Total Physical Memory")
            usedMemory = systemView.get("Used Physical Memory")
            if((physicalMemory != "-" or physicalMemory is not None or physicalMemory != "N/A") and (usedMemory != "-" or usedMemory is not None or usedMemory != "N/A")):
                # result = compareDate(lastMongoBackup,1)
                my_logger.info("The value of the total physical memory is : " + physicalMemory)
                my_logger.info("The value of the used physical memory is : " + usedMemory)

                try:
                    finalPercentage = (int(usedMemory) * 100)/int(physicalMemory)
                except Exception:
                    finalPercentage = 0


                my_logger.info("The percentager of the used memory is : ")
                my_logger.info(finalPercentage)
                if finalPercentage > 90:
                    status = "red"

        except Exception as e:
            my_logger.info(e)
            my_logger.info("The value of exception is above")     



        try:
            WireTigerSize = systemView.get("WireTigerSize")
            wireTigerSize = WireTigerSize.split()
            wireTigerSizeinBytes = int(wireTigerSize[0])

            my_logger.info("The alue of the wireTigerSize in bytes is : ")
            my_logger.info(wireTigerSizeinBytes)

            gb_value = wireTigerSizeinBytes / (1024 * 1024 * 1024)

            if gb_value > 20:
                status = "red"


        except Exception as e:
            my_logger.info(e)

        try:
            uploadFileSizeLimit = systemView.get('uploadFileSizeLimitInMB')
            my_logger.info("The upload file size limit is ")
            my_logger.info(uploadFileSizeLimit)
            if(int(uploadFileSizeLimit) <= 3):
                status = "red"

        except Exception as e:
            my_logger.info(e)

        

        try:
            moreDetails.update({'Parablu Disk Mounted':[systemView.get('parabluDiskMounted')]})
            parabluMounted = systemView.get('parabluDiskMounted')
        except Exception:
            parabluMounted = "Not Mounted"
            


        my_logger.info("=================================Parablu Disk Details===========================================")
        
        
        try:
            my_logger.info("The line number 2383")
            my_logger.info(systemView.get('parabluSize'))
            parabluDiskSize = systemView.get('parabluSize')
            if parabluDiskSize is not None:
                my_logger.info("The line number 2384" + parabluDiskSize)
                my_logger.info("The line number 2384")
                parabluDiskBytes = convert_to_bytes(systemView.get('parabluSize'))
                my_logger.info(parabluDiskBytes)
                my_logger.info("The line number 2385")
                my_logger.info(int(parabluDiskBytes))
            else:
                parabluDiskBytes = convert_to_bytes2(systemView.get('Total Space'))
                my_logger.info("The line number 2395")
        except Exception:
            my_logger.info("The line number 2388")
            parabluDiskBytes = 0
            parabluDiskSize = "N/A"
        
        
        try:
            if parabluMounted == "Not Mounted" or systemView == "N/A":
                parabluDiskBytes = convert_to_bytes2(systemView.get('Total Space'))
                my_logger.info("The parablu disk is not mounted so considering / value")
                my_logger.info("The vlue oif the / parablu is :")
                my_logger.info(parabluDiskBytes)

        except:
            parabluDiskBytes = 0



        # try:
        #     uploadFolder = systemView.get('UploadFolder')
        #     # my_logger.info("The value of the Upload Folder size is : "+ uploadFolder)
        #     uploadFolderBytes = convert_to_bytes(systemView.get('UploadFolder'))
            
        # except Exception as e:
        #     my_logger.info(e)
        #     uploadFolderBytes = 0

        # try:
        #     percentageuploadFolder= (int(uploadFolderBytes) * 100)/int(parabluDiskBytes)
        #     my_logger.info("The value of the poercentage tmp chunk is ")
        #     my_logger.info(percentageuploadFolder)
        #     my_logger.info("This is the try catch")
        # except:
        #     my_logger.info("This is the except catch")
        #     percentageuploadFolder = 0
        #     my_logger.info(percentageuploadFolder)


        # if(percentageuploadFolder > 35):
        #     status = "red"



        try:
            tmpChunkFolder = systemView.get('tmpFolder')+"B"
            tmpChunkFolderBytes = convert_to_bytes(systemView.get('tmpFolder'))
            my_logger.info("the value of the tmpchunk folder in byters")
            my_logger.info(tmpChunkFolderBytes)
        except Exception:
            tmpChunkFolderBytes = 0
            tmpChunkFolder = "0"+"B"
        
        try:
            percentagetmpChunk = (int(tmpChunkFolderBytes) * 100)/int(parabluDiskBytes)
        except:
            percentagetmpChunk = 0


        if(percentagetmpChunk > 25):
            status = "red"



        # try:
        #     fFolderSize = systemView.get('fFolderSize')
        #     fFolderSizeBytes = convert_to_bytes(systemView.get('fFolderSize'))
        # except Exception as e:
        #     my_logger.info(e)
        #     fFolderSizeBytes = 100000000000000000
        #     fFolderSize = "N/A"


        # if(fFolderSizeBytes > 8192):
        #     status = "red"



        try:
            patchfileSizeBytes = convert_to_bytes(systemView.get('patchFileSize'))
            my_logger.info("The Paych file iuze oid : ")
            my_logger.info(patchfileSizeBytes)
        except Exception:
            my_logger.info("This is the exception : ")
            patchfileSizeBytes = 0

        
        
        if(patchfileSizeBytes > config.patchfileSizeBytes):
            patchfileSizeColor = "red"



        try:
            syncFolder = systemView.get('SyncFolderSize') +"B"
            syncFolderBytes = convert_to_bytes(systemView.get('SyncFolderSize'))
            my_logger.info("The Sync folder Bytes is : ")
            my_logger.info(syncFolderBytes)

        except Exception:
            syncFolder = "0"
            syncFolderBytes = 0

        if(syncFolderBytes > config.syncFolderBytes):
            status = "red"



        try:
            backupPolicy = systemView.get('BackupPolicy')
        except Exception:
            backupPolicy = "N/A"


        if(backupPolicy != "enabled"):
            status = "red"


        
        try:
            swapSpace = systemView.get('Swap Memory / Disabled')
            my_logger.info("The value of the swap space is : ")
            my_logger.info(swapSpace)
        except Exception:
            swapSpace = 0

        if(int(swapSpace) < int(physicalMemory) * 2):
            status = "red"


    except Exception as e:
        my_logger.info("The below is the exception raised")
        my_logger.info(e)

    my_logger.info("==========================================================================================================================================")


    licenceAdillllll = LicenceDataAddil.find_one({'cloudName':client}, sort=[('_id', pymongo.DESCENDING)])
    LicenceArray = licenceAdillllll.get('LicenceAdditional')


    # uniqueCount = 0
    # try:
    #     if "ODB Enabled" in LicenceArray:
    #         dataprocListNew = dataprotectionList.find_one({'CloudName':client}, sort=[('_id', pymongo.DESCENDING)])

    #         my_logger.info("The value of the data protectection list is ")
    #         my_logger.info(dataprocListNew)

    #         if dataprocListNew is not None:
    #             typeOfOdbDetails = dataprocListNew.get('MUX-MIX')
    #             my_logger.info("The value of yje type of details is ")
    #             my_logger.info(typeOfOdbDetails)

    #             if typeOfOdbDetails is not None:
    #                 if typeOfOdbDetails == "MUX":
    #                     value = True
    #                 elif typeOfOdbDetails == "MIX":
    #                     value = True
    #                 elif typeOfOdbDetails == "NON-MUX":
    #                     value = True

    #                 else:
    #                     value = False

    #             else:
    #                 latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])
    #                 Muxdatas = colors.find_one({'username':client}, sort=[('_id', pymongo.DESCENDING)])
                    
    #                 if Muxdatas is None:
    #                     clientName = findHostNameWithSystem(client)
    #                     Muxdatas = colors.find_one({'username':clientName}, sort=[('_id', pymongo.DESCENDING)])

    #                 if(Muxdatas.get('MuxType')):
    #                     value = Muxdatas.get('MuxType')    
    #                 else:
    #                     value = Muxdatas.get('MuxType')

    #         else:
    #             latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])
    #             Muxdatas = colors.find_one({'username':userid}, sort=[('_id', pymongo.DESCENDING)])
                
    #             if Muxdatas is None:
    #                 clientName = findHostNameWithSystem(client)
    #                 Muxdatas = colors.find_one({'username':clientName}, sort=[('_id', pymongo.DESCENDING)])

    #             if(Muxdatas.get('MuxType')):
    #                 value = Muxdatas.get('MuxType')    
    #             else:
    #                 value = Muxdatas.get('MuxType')

        
    #     if(value):  
    #         my_logger.info("This value is true")
    #         my_logger.info("They are either Mux or Mix based one drive")
    #         latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])
    #         addCloudPrefixMux = "cloud_"+client+"mux"
    #         my_logger.info("The value of the addCloudPrefixMux at line 3042 is: " + addCloudPrefixMux)
    #         if addCloudPrefixMux in dbs.list_collection_names():
    #             myMachineMuxCollection = dbs[addCloudPrefixMux]
    #         else:
    #             clientMux = findHostNameWithSystem(client)
    #             addCloudPrefixMux = "cloud_"+clientMux+"mux"

    #         myMachineMuxCollection = dbs[addCloudPrefixMux]
            
    #         unique_odbLoginIds = myMachineMuxCollection.distinct('odbLoginId')
    #         my_logger.info("I am in the line 3052")

    #         my_logger.info("The below is the size of the Unique Id's : ")
    #         my_logger.info(len(unique_odbLoginIds))
    #         uniqueIdLength = len(unique_odbLoginIds)
            

    #         for odbLoginId in unique_odbLoginIds:
    #             document = myMachineMuxCollection.find_one({'odbLoginId': odbLoginId},sort=[('DateTime', pymongo.DESCENDING)])
    #             my_logger.info(document)
    #             if document is not None:
    #                 my_logger.info("The value of the percentage is ")
    #                 percentage = document['Details']['percentage']
    #                 my_logger.info(percentage)
    #                 if(int(percentage) > 90):
    #                     uniqueCount = uniqueCount + 1

    #         my_logger.info("============3059==================")

    #     my_logger.info("the value of buckets which exceeded the 50 percentage is ")
    #     my_logger.info(uniqueCount)
    # except Exception as e:
    #     my_logger.info(e)
    #     my_logger.info("I am in Exception ")


    # if uniqueCount > 0:
    #     uniqueCountColor = "red"
    #     uniqueCo = uniqueCount
    # else:
    #     uniqueCountColor = "darkgreen"
    #     uniqueCo = "No Buckets"




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



def findSystemName(cloudName):
    my_logger.info("the value of the cloudname is : ")
    my_logger.info(cloudName)

    cloudTable = CloudName.find_one({'CloudName':cloudName})
    systemName = cloudTable.get("System Name")
    return systemName

def findHostNameWithSystem(cloudName):
    machineDb = "cloud_"+cloudName
    collectionDb = dbs[machineDb]
    machineTable = collectionDb.find()
    SystemName = cloudName
    for i in machineTable:
        if(i['ServerType'] == '0.0'):
            #my_logger.info("The System Name is : " + i['System Name'])
            SystemName = i['System Name']
    return SystemName

    

def checkVersion(input):
    input_version = input  # replace with the actual input version

    if LooseVersion(input_version) < LooseVersion("2.5.4.14"):
        return False
    else:
        return True



def kbToGb(value):
    kbValue = int(value)
    gb = kbValue / (1024 * 1024)
    return gb



@admin.route("/dashboard")
def dashboard():
    if not session.get('logged_in'):
        flash("Sorry!!! You have not logged in","warning")
        return redirect(url_for('authentication_blueprint.login'))
    
    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))



    #Session time counter
    # logged_in_at = datetime.fromtimestamp(session['logged_in_at'])
    # elapsed_time = datetime.now() - logged_in_at
    # session_time = str(elapsed_time)

    

# check_logged_in()

    clients = []
    data = list(auth.find())
    
    CloudNameList =  CloudName.find()
    my_logger.info("This is the Cloudname list")

    userData = usersTotal.find()
    # count = parablu_db.count_documents({})
    # for i in CloudNameList:
    #     if i['CloudName'] in clients:
    #         continue
    #     else:
    #         clients.append(i['System Name'])
    for i in CloudNameList:
        print("This is line 110")
        clients.append(i['CloudName'])


    my_logger.info("The total clients are : ")
    my_logger.info(clients)

    my_logger.info("==========================================================================================================")
    count = len(clients)
    new = []
    news = {}
    flag = 0
    scorecards,deviceProc,fullBackup = 0,0,0
    
    
    owners = set([d['username'] for d in data if 'username' in d])



    my_logger.info("Tje total Clintes size is")
    my_logger.info(len(clients))
    my_logger.info(clients)

    for client in clients:
        asd = CloudName.find_one({'CloudName':client})
        new.append(asd)

        # color = checkHealth(client)
        color = "warning"
        dashboardColorCheck = dashboardColor.find_one({"cloudName":client},sort=[('_id', pymongo.DESCENDING)])
        if dashboardColorCheck is not None:

            color = dashboardColorCheck.get("status")
            if color is None:
                color = checkHealth(client)
                my_logger.error("The color is not present")

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

        news.update({client:color})
        

    print("This is line 239 ========================================================================")
    usersData = auth.find({})
    cloudname_to_owner = {}

    print("Thos os line 239 ")
    #This is for owners
    for ownerId in clients:
        CloudNme = CloudName.find_one({'CloudName':ownerId})
        CloudUser_id = CloudNme.get('Owner')
        if CloudUser_id == "nothing":
            cloudname_to_owner.update({ownerId: "Not Yet Assigned"})
        else:
            user = auth.find_one({"_id": CloudUser_id})
            if user is None:
                cloudname_to_owner.update({ownerId: "Not Yet Assigned"})
            else:
                cloudname_to_owner.update({
                    ownerId: user.get('username')
                })

    # cursorFinal = mycollection.find({}).sort("DateTime",-1).limit(1)
    cloudname_to_date = {}
    insideList = []         

    my_logger.info("the value of Clients is below: ")
    my_logger.info(clients)

    for cliList in clients:
        my_logger.info("The Value of CliList is")
        my_logger.info(cliList)
        addCloud = "cloud_" + cliList
        my_logger.info("The Value of the addCloud: ")
        cloudName_to_Date = {}
        ClouddateDataCollection = dbs[addCloud]

        # Use aggregation to get the latest document for each unique CloudName
        pipeline = [
            {"$sort": {"_id": -1}},
            {"$group": {"_id": "$CloudName", "latest_doc": {"$first": "$$ROOT"}}}
        ]

        cursor = ClouddateDataCollection.aggregate(pipeline)

        for i in cursor:
            cloudname = i['latest_doc']['CloudName']
            datetimeCloud = i['latest_doc']['Date & Time ']

            # Convert 'ServerType' to an integer
            machine_type = int(float(i['latest_doc'].get('ServerType', 0)))

            if machine_type == 0:
                cloudname_to_date[cloudname] = datetimeCloud
            else:
                my_logger.info("The value of the cloudname is: " + cloudname)
                my_logger.info(datetimeCloud)
                cloudname_to_date[cloudname] = datetimeCloud

        # Add a default value for datetime outside the loop
        datetimeCloud = None

    my_logger.info("The below is the inside list data: ")
    my_logger.info(insideList)



    three_hours_ago = datetime.now() - timedelta(hours=3)
    formatted_time = three_hours_ago.strftime("%d %b %Y %H:%M")


    print("The formatted time is : ")
    print(formatted_time)

    #This is for the production and others
    cloudname_to_type = {}
    for ownerId in clients:
        print("The value of the ownerid is : "+ ownerId)
        CloudNme = CloudName.find_one({'CloudName':ownerId})
        CloudUser_id = CloudNme.get('MachineType')
        if CloudUser_id is None:
            cloudname_to_type.update({ownerId: "other"})
            print("the owner id "+ ownerId + "have machineType null")
        else:
            if CloudUser_id == "prod":
                my_logger.info("The production is")
                my_logger.info(CloudUser_id)
                cloudname_to_type.update({ownerId: "production"})
            cloudname_to_type.update({ownerId: CloudUser_id})
            print("the owner id "+ ownerId + "have machineType"+CloudUser_id)
            

    return render_template('dashboard/dashboardMain.html',cloudname_to_owner= cloudname_to_owner,formatted_time=formatted_time,cloudname_to_type=cloudname_to_type,cloudname_to_date = cloudname_to_date,now = now, datas=new, owners=owners,counts=count,colorsss = news)

import re

@admin.route("/dashboardsssss/<string:client>")
def Test(client):
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))


    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))


    print("The value of the line 344 is : ")
    print("The client valiue is "+client)


    my_logger.info("The valie on line 371 is : ")
    my_logger.info("=====================================================================")

    

    # res = client.partition(".parablu.com")[0]
    my_logger.info("The value of the client is "+client)
    addCloudPrefix = "cloud_"+client

    # cloudNam = LicenceData.find({"System Name" :client})

    mycollection=dbs[addCloudPrefix]
    cursor = mycollection.find()
    insideList = [] 
    cloudNaming = "N/A"
    for i in cursor:
        if i['System Name'] in insideList:
            continue
        else:
            insideList.append(i['System Name'])

    color = "healthy"

    a = {}


    try:
        totalMachineList = machineList.find_one({"cloudName" : client},sort=[("_id", pymongo.DESCENDING)])

        finalMachineList = totalMachineList.get("MachinesList")

    #set_a = set(finalMachineList)
    # set_b = set(list_b)

    #common_elements = set_a.intersection(insideList)
    #elements_to_add = set_a.difference(insideList)

    #insideList = list(common_elements.union(elements_to_add))
    except:
        finalMachineList = []
    my_logger.info("=====================================================================================================")
    my_logger.info(finalMachineList)
    my_logger.info(insideList)
    if finalMachineList is not None and len(finalMachineList) > 0:
        insideList = finalMachineList
    my_logger.error(".....................................++++++++++++++++++++++++++++++++++++++++++++++++++")
    insideListCursor = []
    for i in insideList:
        cursorFinal = mycollection.find({'System Name':i}).sort("Date & Time ",-1).limit(1)
        for j in cursorFinal:
            print("The Free Space is printed below")
            print(j['Free Space'])
            MachineType = j['ServerType']
            print(MachineType)
            MachineTypeValue = int(float(MachineType))
            j.update({'MachineTypeValue':MachineTypeValue})

            #Calculating the percentages of the Physical Memory
            TotalPhy = j['Total Physical Memory']
            UsedPhy = j['Used Physical Memory']
            Freephy = j['Free Physical Memory']


            my_logger.info("=====================================================================")
            my_logger.info("The value of the available")
            Available = j['Available']
            my_logger.info(Available)

            try:
                availablePercentage = (100 * int(Available))/ int(TotalPhy)
            except Exception as e:
                my_logger.info(e)
                my_logger.info("This is exception in line 742")
                availablePercentage = 0


            finalAvailablePercentage = 100 - availablePercentage
            j.update({"finalAvailablePercentage":finalAvailablePercentage})


            try:
                UsedPercentage = (100 * int(UsedPhy))/int(TotalPhy)
            except Exception:
                UsedPercentage = 0
            
            try:
                FreepercentageOld = (100 * int(Freephy))/int(TotalPhy)
            except Exception:
                FreepercentageOld = 0

            TotalSys = j['Total Space']
            UsableSys = j['Free Space']

            TotalSyss = re.sub(r' GB','',TotalSys)
            UsableSyss = re.sub(r' GB','',UsableSys)

            try:
                UsablePercentage = (100 * int(float(UsableSyss)))/int(float(TotalSyss))
            except ZeroDivisionError:
                UsablePercentage = 0


            if(UsedPercentage < 90):
                usedPhyColor = "darkgreen"
            else:
                usedPhyColor = "red"
            
            Freepercentage = 100 - FreepercentageOld
            j.update({"usedPhyColor":usedPhyColor})
            j.update({"UsedPercentage":UsedPercentage})
            j.update({"Freepercentage":Freepercentage})
            j.update({"UsablePercentage":UsablePercentage})


            swapSpace = j['Swap Memory / Disabled']
            my_logger.info("The value of the swap Space is ")
            my_logger.info(swapSpace)

            if(int(swapSpace) >= int(TotalPhy) * 2):
                swapSpaceColor = "darkgreen"
            else:
                swapSpaceColor = "red"
            

            my_logger.info("The swap space color is : " + swapSpaceColor)
            j.update({"swapSpaceColor":swapSpaceColor})

    
            try:
                nightlyRestart = j['lastNightlyRestart']
                if nightlyRestart is not None or nightlyRestart != "N/A" or nightlyRestart != "0" or nightlyRestart != 0:
                    my_logger.info("The value of the nightly restart us ")
                    my_logger.info(nightlyRestart)
                    my_logger.info("I am in line 2637")

                    my_logger.info("The value of the line 951")
                    my_logger.info("============THIS IS LINE 952=======================================================")
                    recordedDate = j['Date & Time ']
                    my_logger.info('the recorded dare time is ')
                    my_logger.info(recordedDate)
                    recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                    recordedDate = recordedDate.strftime("%b %d %Y %H:%M")
                    my_logger.info("=============THIS IS LINE 958==================================================")
                    my_logger.info(recordedDate)


                    date = nightlyRestart.replace('IST', '+0530')
                    date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                    formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')
                    # last_update = datetime.strptime(date, "%a %b %d %H:%M:%S %Z %Y")


                    my_logger.info("The value of the formated date")
                    my_logger.info(formatted_date2)



                    my_logger.info("====================LINE 972============================================")
                    # date_format = "%b %d %Y %H:%M"

                    nightlyRestartColor = compareDateWithDays(recordedDate,formatted_date2,1)
                    my_logger.info("The value of the Nightly Restart Color")
                    my_logger.info(nightlyRestartColor)
                    # recievedTime = datetime.strptime(recordedDate, date_format)
                    # lastNightlyRestartTime = datetime.strptime(formatted_date2, date_format)
                    # difference = recievedTime - lastNightlyRestartTime
                    # my_logger.info("====================LINE 974============================================")

                    # my_logger.info("The value of the line 974")
                    # my_logger.info(difference)
                    # my_logger.info(difference.days)
                    # my_logger.info("The above is the difference in days")
                    # if difference.days > 1:

                    # # if(compareDate(nightlyRestart,1)):
                    #     my_logger.info("I am in this line 2639")
                    #     nightlyRestartColor = "red"         
                    # else:
                    #     my_logger.info("I am in this line 2642")
                    #     nightlyRestartColor = "darkgreen"
                
                else:
                    nightlyRestartColor = "red"

                j.update({"nightlyRestartColor":nightlyRestartColor})

            except Exception:
                my_logger.info("I am in line 2651")
                my_logger.info("I am in the exception")
                nightlyRestartColor = "red"
                j.update({"nightlyRestartColor":nightlyRestartColor})


            parabluSizeBytes = 0
            parabluUsedBytes = 0

            my_logger.info("---------------------------------THE LINE 868-------------------------------------------------------------------------")

            try:
                parabluSize = j['parabluSize']
                my_logger.info("The value in line 870")
                my_logger.info(parabluSize)


                try:
                    if parabluSize is not None or parabluSize != "N/A":
                        parabluSizeBytes = 0
                        valueparabluSize = parabluSize[-1]
                        parabluSize = float(parabluSize[:-1])
                        my_logger.info(parabluSize)
                        my_logger.info("The value in line 880")
                        #j.update({"parabluSizeSystem":str(parabluSize)+"GB"})
                        if(valueparabluSize == "T"):
                            parabluSizeBytes = parabluSize * 1024 * 1024 *1024
                            j.update({"parabluSizeSystem":str(parabluSize)+"TB"})
                            #parabluSize = parabluSize * 1024
                        elif(valueparabluSize == "G"):
                            parabluSizeBytes = parabluSize * 1024 * 1024
                            j.update({"parabluSizeSystem":str(parabluSize)+"GB"})
                        else:
                            j.update({"parabluSizeSystem":"N/A"})
                    else:
                        parabluSize = "N/A"
                        j.update({"parabluSizeSystem":parabluSize})

                except Exception as e:
                    my_logger.info(e)
                    my_logger.info("This is line 882")
                    j.update({"parabluSizeSystem":"N/A"})
                                

            except Exception as e:
                my_logger.info("The error in the line 841")
                my_logger.info(e)
                print(e)
                print("This is line number 841")
                j.update({"parabluSizeSystem":"N/A"})

            my_logger.info("===============================================PARABLU USED========================================================")

            try:
                parabluUsed = j['parabluUsed']
                print("The value of the 890 is ")
                print(parabluUsed)
                my_logger.info("The error in the line 857")
                my_logger.info(parabluUsed)
                my_logger.info("The error in the line 859")
                my_logger.info("The error in the line 895")
                parabluUsedBytes = 0
                try:
                    if parabluUsed is not None or parabluUsed != "N/A":
                        my_logger.info("This is line 1140...............")
                        my_logger.error(parabluUsed)
                        valuetype = parabluUsed[-1]
                        parabluUsed = float(parabluUsed[:-1])
                        my_logger.info(parabluUsed)
                        my_logger.info(".........................Line 1142")
                        my_logger.info(parabluUsed)
                        my_logger.info("The value in line 880")
                        my_logger.info(valuetype)
                        if(valuetype == "T"):
                            parabluUsedBytes = parabluUsed *1024*1024*1024
                            j.update({"parabluUsedSystem":str(parabluUsed)+"TB"})
                        elif(valuetype == "G"):
                            my_logger.info("...................................Line 1168")
                            my_logger.info(parabluUsed)
                            parabluUsedBytes = parabluUsed * 1024 *1024
                            j.update({"parabluUsedSystem":str(parabluUsed)+"GB"})

                        elif(valuetype == "M"):
                            my_logger.info("...................................Line 1174")
                            my_logger.info(parabluUsed)
                            parabluUsedBytes = parabluUsed * 1024 
                            j.update({"parabluUsedSystem":str(parabluUsed)+"MB"})
                        else:

                            j.update({"parabluUsedSystem":"N/A"})
                    else:
                        parabluUsed = "N/A"
                        j.update({"parabluUsedSystem":"N/A"})
                    

                except Exception:
                    my_logger.info("This is line 1151 in parablu used")
                    j.update({"parabluUsedSystem":"N/A"})

            except Exception as e:
                my_logger.info("The error in the line 841")
                my_logger.info(e)
                print(e)
                print("This is line number 841")
                j.update({"parabluUsedSystem":"N/A"})


            try:
                my_logger.info("This is line 924")
                my_logger.info(parabluUsed)
                my_logger.info(parabluSize)
                percentageUserdBytes = (100 * parabluUsedBytes)/parabluSizeBytes
                my_logger.info("This is line 939")
                my_logger.info(percentageUserdBytes)

            except Exception as e:
                my_logger.info("the value is in 926")
                percentageUserdBytesColors = "red"
                my_logger.info(e)
                percentageUserdBytes = 0
                

            if percentageUserdBytes > 80:
                percentageUserdBytesColors = "red"
            else:
                percentageUserdBytesColors = "darkgreen"

            my_logger.info("the percentage used bytes are: ")

            my_logger.info(percentageUserdBytes)

            j.update({"percentageUserdBytes":percentageUserdBytes})
            j.update({"percentageUserdBytesColors":percentageUserdBytesColors})


            try:
                parabluAvailable = j['parabluDiskAvailable']
                my_logger.info("The value of 963")
                my_logger.info("The valiue pf yje parablu Availanle")

                my_logger.info(parabluAvailable)
                if parabluAvailable is not None or parabluAvailable != "N/A":

                    availableValue = parabluAvailable[-1]
                    my_logger.info(".......................................availableValue")
                    my_logger.info(availableValue)
                    parabluAvailable = float(parabluAvailable[:-1])
                    my_logger.info(parabluAvailable)

                    my_logger.error("===============LINE 1231======================================================================")
                    my_logger.info("The value of the Parablu Available is ")
                    my_logger.info(parabluAvailable)
                    my_logger.error("========================LINE 1231================================================================")
                    my_logger.info("The value in line 970")
                    if(availableValue == "T"):
                        my_logger.info("This is the TB value")
                        j.update({"parabluDiskAvailableSize":str(parabluAvailable)+"TB"})
                    elif(availableValue == "G"):
                        j.update({"parabluDiskAvailableSize":str(parabluAvailable)+"GB"})
                    else:
                        j.update({"parabluDiskAvailableSize":"N/A"})
                    #j.update({"parabluDiskAvailableSize":str(parabluAvailable)+"GB"})

                else:
                    parabluAvailable = "N/A"
                    j.update({"parabluDiskAvailableSize":"N/A"})

                
            except Exception as e:
                parabluUsedBytes = 0
                j.update({"parabluDiskAvailableSize":"N/A"})


            try:
                parabluAvailable = j['parabluDiskAvailable']
                my_logger.info("The value of 963")
                my_logger.info("The valiue pf yje parablu Availanle")

                my_logger.info(parabluAvailable)
                if parabluAvailable is not None or parabluAvailable != "N/A":

                    availableValue = parabluAvailable[-1]
                    my_logger.info(".......................................availableValue")
                    my_logger.info(availableValue)
                    parabluAvailable = float(parabluAvailable[:-1])
                    my_logger.info(parabluAvailable)

                    my_logger.error("===============LINE 1231======================================================================")
                    my_logger.info("The value of the Parablu Available is ")
                    my_logger.info(parabluAvailable)
                    my_logger.error("========================LINE 1231================================================================")
                    my_logger.info("The value in line 970")
                    if(availableValue == "T"):
                        my_logger.info("This is the TB value")
                        availableDiskInBytes = parabluAvailable * 1024 * 1024 * 1024
                    elif(availableValue == "G"):
                        availableDiskInBytes = parabluAvailable * 1024 * 1024 



                my_logger.info("-------------------------------------LINE 1256-------------------------------------------------")
                my_logger.info(parabluAvailable)
                my_logger.info("---------------------------------------------LINE 1256-----------------------------------------")
                my_logger.info(parabluSizeBytes)
                percentageAvailable = (100 *availableDiskInBytes)/parabluSizeBytes
                
            except Exception:
                percentageAvailableColor = "red"
                percentageAvailable = 0


            my_logger.info("The value of the percentage available is ")
            my_logger.info("The line of yje 978")
            my_logger.info(percentageAvailable)


            if percentageAvailable < 20:
                percentageAvailableColor = "red"
            else:
                percentageAvailableColor = "darkgreen"

            j.update({"percentageAvailableColor":percentageAvailableColor})
            j.update({"percentageAvailable":percentageAvailable})



            

            my_logger.info("========================THE LINE NUMBER 1165======================================")

            lastMongoUpdateColor = "red"
            try:
                lastMongoUpdate = j['lastMongoUpdate']
                if lastMongoUpdate is not None or lastMongoUpdate != "N/A" or lastMongoUpdate != "0" or lastMongoUpdate != 0:
                   
                    recordedDate = j['Date & Time ']
                    my_logger.info("=================------------------+++++++++++++++++LINE NUMBER 1177++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                    
                    recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                    recordedDate = recordedDate.strftime("%b %d %Y %H:%M")

                    date = lastMongoUpdate.replace('IST', '+0530')
                    date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                    formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')

                    lastMongoUpdateColor = compareDateWithDays(recordedDate,formatted_date2,3)
                    my_logger.info("=================------------------+++++++++++++++++LINE NUMBER 1180++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                    
                    my_logger.info("The value of the Mongo Restart Color")
                    my_logger.info(lastMongoUpdateColor)

                    my_logger.info("========================THE LINE NUMBER 1179======================================")
                
                else:
                    lastMongoUpdateColor = "red"

                j.update({"lastMongoUpdateColor":lastMongoUpdateColor})

            except Exception as e:
                my_logger.info("I am in line 2651")
                my_logger.info("I am in the exception")
                my_logger.error(e)
                lastMongoUpdateColor = "green"
                j.update({"lastMongoUpdateColor":lastMongoUpdateColor})

            my_logger.info("========================THE LINE NUMBER 1193======================================")
                

            print("The new Dictionary is here")
            print(j)
            insideListCursor.append(j)
            # insideListCursor.append(a)



        status = "warning"

        scorecards,deviceProc,fullBackup = 0,0,0 
        #MachineTypeData = mycollection.find_one({'System Name':i},sort=[("Date & Time ",pymongo.DESCENDING)])
        # for u in MachineTypeData:
        #MachineType = MachineTypeData.get('ServerType')
        #MachineTypeValue = int(float(MachineType))
        print("The value of the Machine Type is")
        #if MachineTypeValue == 0:
            #color = checkHealth(client)
        


        color = "warning"
        dashboardColorCheck = dashboardColor.find_one({"cloudName":client},sort=[('_id', pymongo.DESCENDING)])
        if dashboardColorCheck is not None:

            color = dashboardColorCheck.get("status")
            if color is None:
                color = checkHealth(client)
                my_logger.error("The color is not present")

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

    return render_template("dashboard/systemview.html",cloudName = client,color= color,datas = insideListCursor,res = client)




@admin.route("/error502")
def adf():

    delete_User = deletedUs_ers.find_one({"cloudName":"karsan"},sort=[('_id', pymongo.DESCENDING)])
    delete_userValue = delete_User.get("DeletedUsers")
    print(delete_userValue)
    return delete_userValue


import concurrent.futures

import requests

@is_logged_in
@admin.route("/dashboard/<string:client>")
def client(client):
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])
    

    print("The value of the line 551 is : ")
    print("The client valiue is "+client)
    my_logger.info("The value of the line 585 is " + client)

    jack = {}
    machines = dbs["MachinesDB"]
    ##Need to add fast way of getting the value
    licence = colors.find_one({'username':client}, sort=[('_id', pymongo.DESCENDING)])

    my_logger.info("The value of the client is : " + client)
    print("The vakue of the client is : " + client)

    # print("the value of the fullBackupis :" + licence.get('fullBackup'))
    # latest_active_data = usersTotal.find_one({'username':client}, sort=[('_id', pymongo.DESCENDING)])
    asdf = []
    # Printing the data inserted
    print(client)
    CloudTable = CloudName.find_one({'CloudName':client},sort=[("Date & Time ",-1)])
    # res = client.partition(".parablu.com")[0]
    # print("The value of res is :"+res)
    addCloudPrefix = "cloud_"+client

    print("The value in line 619 is : "+ addCloudPrefix)

    usersTotalTable = usersTotal.find_one({'Cloud Name':client}, sort=[('_id', pymongo.DESCENDING)])

    mycollection=dbs[addCloudPrefix]
    my_logger.info("The value of the addcloudPrefix is : "+ addCloudPrefix)

    my_logger.info("The value of the client is : 524" + client)

    print(mycollection)

    #Get the System name out of the cloudname
    SysteNam = findSystemName(client)

    cursor = mycollection.find_one({'CloudName':client,'ServerType':'0.0'}, sort=[('_id', pymongo.DESCENDING)])
    my_logger.info("The value of the cursor is : ")
    my_logger.info(cursor)
    print("This is the line 630 and : ")
    print(cursor)
    insideList = []
    my_logger.info("The value of the cursor is above") 

    my_logger.info("The value of insideListCursor is : ")

    active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])

    news = {}
    news2= {}

    # for i in active_data:
    my_logger.info(active_data)
    try:
        active_users = int(float(active_data.get('Active Users')))
        print(active_users)
    except Exception:
        active_users = 0
    try:
        cloname = active_data.get('Cloud Name')
    except Exception:
        cloname = "N/A"
    my_logger.info("----------------------------------------------------------------LINE 645---------------------------------------------------")

    my_logger.info("---------------------------------------------BELOW IS THE ACTIVE USERS AND FULL BACKUP------------------------------------")
    try:
        dataprocListNew = dataprotectionList.find_one({'CloudName':cloname}, sort=[('_id', pymongo.DESCENDING)])
        fullBackupDataProc = int(dataprocListNew.get("fullbackupCompleted").replace(",",""))
        atleastOneUser = int(dataprocListNew.get("atleastOneDevice").replace(",",""))
        my_logger.info("=======----------------------------------------------------++++++++++++++++++++++++++++++++++++++++++")
        my_logger.info(atleastOneUser)
        activeUsers = int(dataprocListNew.get("activeUsers").replace(",",""))
    except:
        fullBackupDataProc = 0
        activeUsers = "N/A"
    

    my_logger.info("The Ful backup value is :" + str(fullBackupDataProc))
    news.update({'Active Users':[activeUsers,100]})
    jack.update({'No. of Active Users':[activeUsers,100]})

    my_logger.info("---------------------------------------------ABOVE IS THE ACTIVE USERS AND FULL BACKUP------------------------------------")


    # news.update({'CloudName':[cloname]})
#    news.update({'Active Users':[active_users,100]})
 #   jack.update({'No. of Active Users':[active_users,100]})
    # nosOfBackup = i['Nos_Backup']
    # news.update({'Number of Backup Users Allowed':[nosOfBackup]})
    # nosofSync = i['Nos_Sync']
    # news.update({'Nos of Sync Users Allowed':[nosofSync]})
    try:
        nosofBks = int(float(active_data.get('Nos of BK\'s')))
        my_logger.info("Number of Bks are :")
        my_logger.info(nosofBks)
    except Exception:
        nosofBks = 0
    news.update({'Number of Blukrypts':[nosofBks]})
    try:
        active_user_with = active_data.get('Active_user_with_device')
        final_active = active_user_with.replace(",", "")

    except Exception:
        final_active = 0
    
    print("I am in line 681")

    

    activeDevice = int(float(final_active))
    try:
        percentageactiveDevice = (activeDevice * 100)/active_users
    except ZeroDivisionError:
        percentageactiveDevice = 0

    jack.update({'Users with at least one device assigned':[activeDevice,percentageactiveDevice]})
    try:
        activeNodevice = int(float(active_data.get('Active_user_with_nodevice')))
    except Exception:
        activeNodevice = 0
    
    try:
        percentageactiveNoDevice = (activeNodevice * 100)/active_users
    except ZeroDivisionError:
        percentageactiveNoDevice = 0

    jack.update({'No. of users without device registered':[activeNodevice,percentageactiveNoDevice]})

    try:
        restoreAttempts = int(float(active_data.get('Restore Attempts')))
    except Exception:
        restoreAttempts = 0
    
    news.update({'Number of Restore Attempts (Last 30 days)':[restoreAttempts]})
        # productVersion = i['product_version']
        # news.update({'product_version':productVersion})
    
    currentlyRunningBackupCount = "N/A"
    totalStorageUtilized = "N/A"
    totalActualStorageUtilized = "N/A"
    


    my_logger.info("I am in line 707")
    

    my_logger.info("This is the line number 741")
    AADTokenExpiryColor = "red"
    AADExpiredOrNot = "N/A"

    try:
        dataprocList = dataprotectionList.find_one({'CloudName':cloname}, sort=[('_id', pymongo.DESCENDING)])
        currentlyRunningBackupCount = dataprocList.get("currentlyRunningBackupCount")
        totalStorageUtilized = dataprocList.get("totalStorageUtilized")
        totalActualStorageUtilized = dataprocList.get("totalActualStorageUtilized")
        AADExpiredOrNot = "N/A"
        AADTokenExpiryColor = "red"
        try:
            
            AADTokenExpiry = dataprocList.get("AADTokenExpiry")
            if AADTokenExpiry is not None:
                if AADTokenExpiry == "317":
                    my_logger.info("The AAD Token Expiry")
                    AADTokenExpiryColor = "red"
                    AADExpiredOrNot = "Expired"
                elif AADTokenExpiry == "Expired":
                    my_logger.info("The AAD is Expired")
                    AADExpiredOrNot = "Expired"
                elif AADTokenExpiry == "Active":
                    AADTokenExpiryColor = "darkgreen"
                    AADExpiredOrNot = "Active"
                else:
                    AADExpiredOrNot = "N/A"
                    AADTokenExpiryColor = "red"
            else:
                AADExpiredOrNot = "N/A"
                AADTokenExpiryColor = "red"

        except Exception as e:
            my_logger.info(e)
            AADTokenExpiryColor = "red"
            AADExpiredOrNot = "N/A"
        
    except:
        currentlyRunningBackupCount = "N/A"
        totalStorageUtilized = "N/A"
        totalActualStorageUtilized = "N/A"
        AADExpiredOrNot = "N/A"



    # currentlyRunningBackupCount = data["clo dOverviewElement"]["currentlyRunningBackupCount"]
    news.update({'Currently Running Backups':[currentlyRunningBackupCount]})  
    # totalStorageUtilized = data["cloudOverviewElement"]["totalStorageUtilized"]
    news.update({'Total Storage Utilized':[totalStorageUtilized]})  
    news.update({'Actual Storage Utilized':[totalActualStorageUtilized]})  
    

    print(len(news))
    print("The Length of the News is :" + str(len(news)))
    print("The host Name is :" + client)
    # print("The host name " + client + " is " + str(len(active_data)))


    # print("The value of the CliudName in 764 is "+cloudName)
    #hostClientName = findSystemName(client)

    hostClientName = client

    print("The value of the HostClientName is " +hostClientName )
    my_logger.info("The HostClientName is : "+ hostClientName)

    if ".parablu.com" in hostClientName:
        pass
    else:
        hostClientName = findHostNameWithSystem(client)
        print("The line 777 is : "+ hostClientName)


    muxCount = 0
    try:
        HOSTS = [(hostClientName, 443),]
        
        timeout = 10
        with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
            for hostinfo in e.map(lambda x: get_certificate(x[0], x[1]), HOSTS,timeout = timeout):
                print_basic_info(hostinfo)

        print("Check this line")
        print(hostinfo.cert.not_valid_after)
        sslExpiry = hostinfo.cert.not_valid_after
        curr_time = round(time.time()*1000)
        print("Milliseconds since epoch:",curr_time)

        sslExp = datetime.strptime(str(sslExpiry), "%Y-%m-%d %H:%M:%S")

        sslExper = sslExp.strftime("%d %b %Y")
        sslMilli = int(sslExpiry.timestamp() * 1000)

        totalDays = sslMilli - curr_time
        print(totalDays)

        seconds, totalDays = divmod(totalDays,1000)
        minutes, seconds = divmod(seconds, 60)
        hours, minutes = divmod(minutes, 60)
        days, hours = divmod(hours, 24)
        seconds = seconds + totalDays/1000

        duration = days
        print(days)
    except:
        duration = "N/A"

    fullBackupNot = 0
    fullBackup = 0


    try:
        if atleastOneUser != 0:
            percentageFullbackup = (fullBackupDataProc * 100) / atleastOneUser
            print(percentageFullbackup)
        else:
            percentageFullbackup = 0
    except Exception:
        percentageFullbackup = 0

    jack.update({"No. of users for whom at least one full backup is completed":[fullBackupDataProc,percentageFullbackup]})

    try:
        scorecardHeard = licence.get('scorecardHeard')
    except Exception:
        scorecardHeard = 0

    try:
        if(scorecardHeard!='0'):
            score_value0 = int(scorecardHeard[:-2].split('(')[0])
            score_value1 = int(scorecardHeard[:-2].split('(')[1])
        else:
            score_value0 = 0
            score_value1 = 0
    except Exception:
        score_value0 = 0
        score_value1 = 0

    print("The Scorecard value is ")
    print(score_value0)
    jack.update({"No. of users whose devices had a heartbeat to the server in the last 30 days":[score_value0,score_value1]})

    try:
        device_proc = licence.get('deviceProtected')
        if(device_proc!='0'):
            device_value0 = int(device_proc[:-2].split('(')[0])
            device_value1 = int(device_proc[:-2].split('(')[1])
        else:
            device_value0 = 0
            device_value1 = 0
        print(device_value0)
    except Exception:
        device_value0 = 0
        device_value1 = 0

    jack.update({"No. of users whose devices have been protected in the last 30 days":[device_value0,device_value1]})

    # for k in serverVer:
    print("The server version")
        # print(k['serverVersion'])

    res = "test"

    
    try:
        validity = usersTotalTable.get('Validity Period')
    except Exception:
        validity = 0

    try:
        serverVersion = usersTotalTable.get('serverVersion')
    except Exception:
        serverVersion = 0
    news.update({"Server Version":[serverVersion]})

    print("What is this")

    my_logger.info("The value of the client")
    # AgentVer = AgentData.find({"cloudName":clo})
    AgentVer = AgentData.find_one({'cloudName':client}, sort=[('_id', pymongo.DESCENDING)])
    my_logger.info(AgentVer)
    my_logger.info("The Above is the Agent Data")
    # for l in AgentVer:
    if(AgentVer is not None):
        try:
            serviceVersion = AgentVer.get('service')
        except Exception:
            serviceVersion = "service|-"
        # print("The Server Version isserviceVersion)
        if serviceVersion is not None:
            serviceSplit = serviceVersion.split('|')
            print(serviceSplit[1])
            news.update({"Agent Version: Windows":[serviceSplit[1]]})
        else:
            news.update({"Agent Version: Windows":"-"})
    else:
        news.update({"Agent Version: Windows":"-"})


    my_logger.info("I am at line 1003")

    if(AgentVer is not None):
        try:
            macVersion = AgentVer.get('mac')
        except Exception:
            macVersion = "mac|-"
        
        if macVersion is not None:
            print("The below is the mac version")
            print(macVersion)
            macSplit = macVersion.split('|')
        # print(serviceSplit[1])
            news.update({"Agent Version: Mac":[macSplit[1]]})
        else:
            news.update({"Agent Version: Mac":"-"})
    else:
        news.update({"Agent Version: Mac":"-"})
    
    my_logger.info("I am at line 1022")


    #my_logger.info("The value of the sslEXper ois:"+sslExper)
    #my_logger.info("The duration of ssl Expiry is "+ duration)
    #my_logger.info("The licence Expiry is"+validity)
    try:
        my_logger.info("==============================================LINE 1485===============================================")
        my_logger.info("The value of line 1486")
        my_logger.info(duration)
        durationColor = "darkgreen"
        if int(duration) <= 7:
            durationColor = "red"
        my_logger.info(sslExper)
        news.update({'SSL Certificate Valid Until':[sslExper,durationColor,"Days to expire"]})
    except:
        news.update({'SSL Certificate Valid Until':["N/A","N/A", "Days to expire"]})


    try:
        my_logger.info("--------------------------------=====================LINE 1498====================================")
        my_logger.info("The validity of theb")
        expiration_date = datetime.strptime(validity, "%d %b %Y %H:%M:%S")
        my_logger.info(validity)
        current_date = datetime.now()
        licenceExpiryColor = "darkgreen"
        difference = expiration_date - current_date
        if difference <= timedelta(days=15):
            licenceExpiryColor = "red"
        my_logger.info(difference)
        news.update({"License Valid Until":[validity,licenceExpiryColor]})
    except:
        licenceExpiryColor = "red"
        news.update({"License Valid Until":["N/A",licenceExpiryColor]})

    my_logger.info("I am at line 1027") 
    licenceAdillllll = LicenceDataAddil.find_one({'cloudName':client}, sort=[('_id', pymongo.DESCENDING)])



    uniqueIdLength = 0
    my_logger.info("I am at line 1031")
    try:
        LicenceArray = licenceAdillllll.get('LicenceAdditional')
    except Exception:
        LicenceArray = []
    my_logger.info("The LicenseArray is : ")
    my_logger.info(LicenceArray)

    storage = {}
    value = False

    news.update({'AAD Auth Token':[AADExpiredOrNot,AADTokenExpiryColor]})  

    my_logger.info("The backup policy=================================")
    

    backupPolicyDataCollection = dbs["backupPolicyList"]

    backupPolicyData = backupPolicyDataCollection.find_one({"cloudName":client}, sort=[('_id', pymongo.DESCENDING)])

    my_logger.info("The value of the clinet is : "+ client)
    my_logger.info("====================================================------------------------LINE 1693--------------------------------------------------------===========================================================")
    my_logger.info(backupPolicyData)
    backupPolicies = []

    if backupPolicyData is not None:
        my_logger.info("I am in line 1697")
        backupPolicies = backupPolicyData.get("backupPolicyList")
        my_logger.info(backupPolicies)
        my_logger.info("The above is the backuppolicies from he line 1696")
        my_logger.info("The Backup Policy having disabled is")
        my_logger.info(len(backupPolicies))
        
    else:
        my_logger.info("I am in line 1703")
        news.update({'Dedup Backup Policy':["N/A","red"]})  

    try:
        dedupBackupPolName = cursor.get("BackupPolicy")
    except Exception as e:
        my_logger.info(e)
        my_logger.info("This is the exception")
        dedupBackupPolName = "N/A"

    if len(backupPolicies) != 0:
        totalNumber = str(len(backupPolicies)) + " Policies"
        my_logger.info("This is backup Policy .............................................................................")
        my_logger.info(dedupBackupPolName)
        news.update({'Dedup Backup Policy':[totalNumber +" "+ dedupBackupPolName,"red"]})  
    else:
        news.update({'Dedup Backup Policy':["No Policies","red"]})  

    my_logger.info("The backup policy=================================")

    print("Below is the Licence Enabled details")

    storageTypeInMachine = active_data.get("StorageType")

    my_logger.info("The Storage type is ")
    my_logger.info(storageTypeInMachine)
    print("Below is the Licence Enabled details")


    if "ODB Enabled" in LicenceArray:
        my_logger.info("This is entering odb enabled")
        storage.update({'Storage Target':["OneDrive"]})
        my_logger.info("The value of thje client in line 957 is"+client)
        my_logger.info("Based on version I need to make it")



        dataProtection = dataprotectionList.find_one({'CloudName': client}, sort=[('_id', pymongo.DESCENDING)])

        my_logger.info(dataProtection)
        my_logger.info("The above is the dataprotection scorecard")

        if dataProtection is not None:

            typeOfOdbDetails = dataProtection.get('MUX-MIX')



            my_logger.info("The Type of ythe details is : ")
            my_logger.info(typeOfOdbDetails)

            if typeOfOdbDetails is not None:

                if typeOfOdbDetails == "MUX":
                    
                    value = True
                    storage.update({'Type':[typeOfOdbDetails]})


                elif  typeOfOdbDetails == "MIX":
                    
                    value = True
                    storage.update({'Type':[typeOfOdbDetails]})

                elif typeOfOdbDetails == "NON-MUX":
                    
                    value = False
                    storage.update({'Type':[typeOfOdbDetails]})

                else:
                    value = False

            else:
                latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])

                Muxdatas = colors.find_one({'username':client}, sort=[('_id', pymongo.DESCENDING)])
                if Muxdatas is None:
                    clientName = findHostNameWithSystem(client)
                    Muxdatas = colors.find_one({'username':clientName}, sort=[('_id', pymongo.DESCENDING)])


                if(Muxdatas.get('MuxType')):
                    value = Muxdatas.get('MuxType')    
                else:
                    value = Muxdatas.get('MuxType')

        else:
            latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])

            Muxdatas = colors.find_one({'username':client}, sort=[('_id', pymongo.DESCENDING)])
            if Muxdatas is None:
                clientName = findHostNameWithSystem(client)
                Muxdatas = colors.find_one({'username':clientName}, sort=[('_id', pymongo.DESCENDING)])


            if(Muxdatas.get('MuxType')):
                value = Muxdatas.get('MuxType')    
            else:
                value = Muxdatas.get('MuxType')
   

    elif "Google Drive Enabled" in LicenceArray:
        storage.update({'Storage target':["Google Drive"]})

    elif(storageTypeInMachine == "azureblob"):
        storage.update({'Storage target':["Azure Blob"]})
    
    elif(storageTypeInMachine == "ibmCloud"):
        storage.update({'Storage target':["IBM Cloud"]})

    elif(storageTypeInMachine == "swift"):
        storage.update({'Storage target':["Swift"]})

    elif(storageTypeInMachine == "b2"):
        storage.update({'Storage target':["b2"]})

    elif(storageTypeInMachine == "s3"):
        storage.update({'Storage target':["S3"]})


    elif(storageTypeInMachine == "aws-s3"):
        storage.update({'Storage target':["aws-s3"]})

    elif(storageTypeInMachine == "localStorage"):
        storage.update({'Storage target':["Local Storage"]})
    else:
        storage.update({'Storage target':["N/A"]})

    muxFileUserSize = 0

    print("the value of Value is here")
    print(value)
    distinct_documents = []
    
    my_logger.info("I am in the line 986")

    if(value):   
        MuxType = "Mux"
        my_logger.info("The line 1005 is ")
        my_logger.info(client)
        latest_active_data = usersTotal.find_one({'Cloud Name': client}, sort=[('_id', pymongo.DESCENDING)])

        addCloudPrefixMux = "cloud_"+client+"mux"



        my_logger.info("The value of the addCloudPrefixMux at line 1017 is: " + addCloudPrefixMux)
        

        if addCloudPrefixMux in dbs.list_collection_names():
            myMachineMuxCollection = dbs[addCloudPrefixMux]
        else:
            clientMux = findHostNameWithSystem(client)
            addCloudPrefixMux = "cloud_"+clientMux+"mux"

        myMachineMuxCollection = dbs[addCloudPrefixMux]
        
        unique_odbLoginIds = myMachineMuxCollection.distinct('odbLoginId')
        my_logger.info("I am in the line 857")
        
        try:
            currentBuckets = documentsMuxCurrent.find_one({'CloudName': client},sort=[("_id", -1)])
            currentBucketsList = currentBuckets.get("CurrentList")
        except:
            currentBucketsList = []
        my_logger.info("The currentBucket List is")
        my_logger.error(currentBucketsList)

        my_logger.info("====================================================================================================")
        if(currentBucketsList is not None and len(currentBucketsList)>0):
            unique_odbLoginIds = currentBucketsList

        my_logger.info("====================================================================================================")

        my_logger.info("The below is the size of the Unique Id's : ")
        my_logger.info(len(unique_odbLoginIds))
        uniqueIdLength = len(unique_odbLoginIds)
        uniqueCount = 0
        for odbLoginId in unique_odbLoginIds:
            if uniqueCount >= 10:
                break
            document = myMachineMuxCollection.find_one({'odbLoginId': odbLoginId},sort=[("_id", -1)])
            my_logger.info("The below is the odb login details")
            my_logger.info("This is the line 1540")
            my_logger.info(document)
            if document:
                my_logger.info("The value of the documents is : ")
                my_logger.info(document)

                distinct_documents.append(document)
                uniqueCount = uniqueCount + 1

        my_logger.info("================================================-------------------------------------------------------------------------")
        
        
        my_logger.info("I am in the line 864................................................")
        print("The Count of the documents are :")
        bucketsCount = len(distinct_documents)
        my_logger.info("The count of the buckets are : ")
        my_logger.info(bucketsCount)
        storage.update({'Total Storage buckets :':[bucketsCount]})
        storage.update({'usersMux':"Click here"})
        getMuxDatauserList = MuxDatauserList.find({"cloudName":client}).sort('_id', pymongo.DESCENDING).limit(1)

        print("I am in line 547")
        print(getMuxDatauserList)
        print("The value of the res is"+cloname)
        for m in getMuxDatauserList:
            print("I am in line 549")
            try:
                muxFileUserSize = len(m['muxFileUsers'])
            except KeyError:
                muxFileUserSize = 0        
    else:
        MuxType = "Non-Mux"


    my_logger.info("==============================THIS IS for OneDrive Mixed Users====================================================")

    oneDriveMixedUsers = dbs["documentOneDriveMis"]

    oneDriveMixed = oneDriveMixedUsers.find_one({"cloudName":client}, sort=[('_id', pymongo.DESCENDING)])

    my_logger.info(oneDriveMixed)
    my_logger.info("The above is the one Drive Mixed details line 1887")
    

    oneDriveMixedUsersList = []

    if oneDriveMixed is not None:
        oneDriveMixedUsersList = oneDriveMixed.get("OneDriveMisList")
        my_logger.info(oneDriveMixedUsersList)
        my_logger.info("The above is the oneDriveMixedUsersList from he line 1696")
        my_logger.info("The oneDriveMixedUsersList  having disabled is")
        my_logger.info(len(oneDriveMixedUsersList))

    else:
        news.update({'OneDrive Id MisMatched Users':["N/A","red"]})

    if len(oneDriveMixedUsersList) != 0:
        oneDriveNumber = str(len(oneDriveMixedUsersList)) + " Users"
        news.update({'OneDrive Id MisMatched Users':[oneDriveNumber,"red"]})  
    else:
        news.update({'OneDrive Id MisMatched Users':["No Users","darkgreen"]})  


    my_logger.info("==============================THIS IS for OneDrive Mixed Users====================================================")


    my_logger.info("The value of the res is : "+res)

    my_logger.info("The value of the distinct object are")
    my_logger.error(distinct_documents)
    # return render_template("dashboard/insideDashboard.html",client=clidatas = insideListCursorent)
    return render_template("dashboard/applicationView.html",uniqueIdLength = uniqueIdLength,active_data = news,MuxDetails = distinct_documents,MuxType=MuxType,store = storage,cloudName = client,activeDevice = activeDevice,activeNodevice=activeNodevice,fullBackupNot = fullBackupNot,fullBackup = fullBackup,device = jack,client = client,muxFileUserSize = muxFileUserSize)


@admin.route('/get_info', methods=['POST'])
def get_info():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))


    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    selection = request.form['selection']
    cloudName = request.form['cloudname']
    print("The below is the CloudName")
    print(cloudName)
    print(selection)


    latest_active_data = usersTotal.find_one({'Cloud Name': cloudName}, sort=[('_id', pymongo.DESCENDING)])
    


    print("The value of the line 344 is : ")
    print("The client valiue is "+cloudName)


    addCloudPrefixMux = "cloud_"+cloudName+"mux"
    

    my_logger.info("The value of the addCloudPrefixMux at line 1017 is: " + addCloudPrefixMux)
        

    if addCloudPrefixMux in dbs.list_collection_names():
        myMachineMuxCollection = dbs[addCloudPrefixMux]
    else:
        clientMux = findHostNameWithSystem(cloudName)
        addCloudPrefixMux = "cloud_"+clientMux+"mux"


    myMachineMuxCollection=dbs[addCloudPrefixMux]    
    unique_odbLoginIds = list(myMachineMuxCollection.distinct('odbLoginId'))


    distinct_documents = []
    for odbLoginId in unique_odbLoginIds:
        document = myMachineMuxCollection.find_one({'odbLoginId': odbLoginId},sort=[('_id', pymongo.DESCENDING)])
        if document:
            distinct_documents.append(document)

    print(distinct_documents)

    for person in distinct_documents:
        if person['odbLoginId'] == selection:
            # Convert ObjectId to string
            person['_id'] = str(person['_id'])
            return jsonify(person)
    return jsonify(error='odbLoginId not found')


@admin.route("/showUsers",methods=['GET','POST'])
def showUsers():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))


    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))


    if request.method == 'POST':
        userid = request.form['userid']
        print("The below is the userid")
        print(userid)
        userList = MuxDatauserList.find({"cloudName" : userid}).sort('_id', pymongo.DESCENDING).limit(1)

        for i in userList:
            LicenceArray = i['muxFileUsers']
    return jsonify({'htmlresponse': render_template('dashboard/muxUser.html',LicenceDetails = LicenceArray)})

@is_logged_in
@admin.route("/download/<string:res>")
def download(res):
    addCloudPrefix = res
    path = "/home/ubuntu/OpcenterFiles/"+addCloudPrefix+"/Machine_statistics.xlsx"
    return send_file(path,as_attachment=True)


def verify_cert(cert, hostname):
    cert.has_expired()


def get_certificate(hostname, port):
    hostname_idna = idna.encode(hostname)
    sock = socket()

    sock.connect((hostname, port))
    peername = sock.getpeername()
    ctx = SSL.Context(SSL.SSLv23_METHOD) # most compatible
    ctx.check_hostname = False
    ctx.verify_mode = SSL.VERIFY_NONE

    sock_ssl = SSL.Connection(ctx, sock)
    sock_ssl.set_connect_state()
    sock_ssl.set_tlsext_host_name(hostname_idna)
    sock_ssl.do_handshake()
    cert = sock_ssl.get_peer_certificate()
    crypto_cert = cert.to_cryptography()
    sock_ssl.close()
    sock.close()

    return HostInfo(cert=crypto_cert, peername=peername, hostname=hostname)


def get_alt_names(cert):
    try:
        ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)
        return ext.value.get_values_for_type(x509.DNSName)
    except x509.ExtensionNotFound:
        return None

def get_common_name(cert):
    try:
        names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
        return names[0].value
    except x509.ExtensionNotFound:
        return None



def get_issuer(cert):
    try:
        names = cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)
        return names[0].value
    except x509.ExtensionNotFound:
        return None

def print_basic_info(hostinfo):
    print(hostinfo.cert.not_valid_after)

def check_it_out(hostname, port):
    hostinfo = get_certificate(hostname, port)
    print_basic_info(hostinfo)


@is_logged_in
@admin.route("/chooseModal",methods=['GET','POST'])
def chooseModal():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))


    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    if request.method == 'POST':
        userid = request.form['userid']
        print("The User Id is "+ userid)
    # print("The hostname is :" + hostname)
    return jsonify({'htmlresponse': render_template('dashboard/hello.html',user = userid)})

from Opcenter import blkuser


@is_logged_in
@admin.route("/activeUsers",methods=['GET','POST'])
def activeModal():
    news = {}
    if request.method == 'POST':
        userid = request.form['userid']
        my_logger.info("The value of the Userid is : "+ userid)
        print("I am in line 1243")
        print("The value of userId is : "+ userid)
        active_data = usersTotal.find_one({'Cloud Name': userid},sort=[("_id",pymongo.DESCENDING)])
        
        # for i in active_data:
        my_logger.info(int(float(active_data.get('Active Users'))))
        active_users = int(float(active_data.get('Active Users')))
        news.update({'Active Users':[active_users,100]})
        # news.update({"No. of Soft Block users":[int(float(active_data.get('softBlock')))]})

        

        cloudNe = userid

        my_logger.info("The clud name is : "+ cloudNe)

        my_logger.info("The above blockedUsers")
        blockedUsers = blkuser.find_one({'cloudName': cloudNe},sort=[("_id",pymongo.DESCENDING)])

        # print(blockedUsers.get('BlockUsers'))
        blockListUsersList = blockedUsers.get('BlockUsers')
        blockListUsersList = list(filter(None, blockListUsersList))
        my_logger.info(blockListUsersList)
        my_logger.info("The Count of BlockList users are : "+ str(len(blockListUsersList)))

        my_logger.info("The above line is missing")
        
        my_logger.info("The User Id is "+ userid)
        news.update({"Blocked Users":[len(blockListUsersList)]})
        blkLength = len(blockListUsersList)


        #Getting the softblock users
        so_FtBloc = soft_blk_usr.find_one({'cloudName': cloudNe},sort=[("_id",pymongo.DESCENDING)])
        sof_tBLok = so_FtBloc.get("SoftBlockUsersList")

        my_logger.info(sof_tBLok)
        softLen = len(sof_tBLok)
        news.update({"SoftBlock Users":[len(sof_tBLok)]})


        #Getting the Deleted users
        Dele_UsBloc = deletedUs_ers.find_one({'cloudName': cloudNe},sort=[("_id",pymongo.DESCENDING)])
        Del_usz = Dele_UsBloc.get("DeletedUsers")

        my_logger.info(Del_usz)
        Del_len = len(Del_usz)
        news.update({"Deleted Users":[len(Del_usz)]})




    return jsonify({'htmlresponse': render_template('dashboard/activeUsers.html',cloudNe = cloudNe,Del_len=Del_len,blkLength =blkLength,softLen=softLen,user = userid,employeelist = news)})

@is_logged_in
@admin.route("/SoftUsers",methods=['GET','POST'])
def SoftUsers():
    if request.method == 'POST':
        cloudName = request.form['userid']
        print("I am printing the cloud name")
        print(cloudName)
        so_FtBlocUser_lis = soft_blk_usr.find_one({'cloudName': cloudName},sort=[("_id",pymongo.DESCENDING)])
        print("The SoftBlock Users List 1001")
        
        sof_tBLok_Lis = so_FtBlocUser_lis.get("SoftBlockUsersList")
        print("The SoftBlock Users List")
        print(sof_tBLok_Lis)
        

    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = sof_tBLok_Lis)})

    

@is_logged_in
@admin.route("/DelUsers",methods=['GET','POST'])
def delUsers():
    if request.method == 'POST':
        cloudName = request.form['userid']
        print("I am printing the cloud name")
        print(cloudName)
        Dele_UsBloc = deletedUs_ers.find_one({'cloudName': cloudName},sort=[("_id",pymongo.DESCENDING)])
        print("The Deleted Users List 1001")
        
        Del_usz = Dele_UsBloc.get("DeletedUsers")
        print("The SoftBlock Users List")
        print(Del_usz)
        

    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = Del_usz)})

    




import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# SMTP Server configuration
smtp_server = 'email-smtp.us-east-2.amazonaws.com'
smtp_port = 587

# Sender and receiver email addresses
sender_email = 'no-reply@parablu.com'


@is_logged_in
@admin.route("/deleteUsers",methods=['GET','POST'])
def deleted_users():    
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))


    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    if(session['accesstype']!="admin"):
        return redirect(url_for('admin.dashboard'))

    if(session['accesstype'] == "admin"):
        usersInList = auth.find()
        # usernames = [doc["username"] for doc in usersInList]


    Machinenames = CloudName.distinct("CloudName")
        
    return render_template("dashboard/deleteUsers.html",users = usersInList,Machinenames=Machinenames)


from bson import ObjectId

@is_logged_in
@admin.route('/delete_account', methods=['GET','POST'])
def delete_account():
    account_ids = request.get_json()['account_id']
    
    print(account_ids)
    value_list = [ObjectId(id) for id in account_ids]
    print("The below is the object Id")
    print(value_list)
    
    for i in value_list:
        document = auth.find_one({'_id': i})
        email = document['email']
        name = document['username']
        filter = {'Owner': name}
        update = {"$set": {"Owner": None}}
        result = CloudName.update_many(filter, update)
        
    auth.delete_many({'_id': {'$in': value_list}})
    return jsonify({'success': True})


@admin.route("/registerUser",methods=["GET","POST"])
def registerUser():
    print("Its coming to this route")
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    if(session['accesstype'] != "admin"):
        return redirect(url_for('admin.dashboard'))
    
    if(session['accesstype'] == "admin"):
        usersInList = auth.find()

    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        accesstype = request.form.get('access_type')
        
        # Check if user already exists in the database
        if auth.find_one({'$or': [{'username': username}, {'email': email}]}):
            user_exists = True
            return render_template('dashboard/deleteUsers.html', user_exists=user_exists,users = usersInList)

        # If user does not exist, insert into the database
        hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')  # String instead of bytes
        auth.insert_one({'username': username, 'email': email, 'password': hashed_password,'accessType':accesstype})
        print('Successfully added to the database')

        # Set a variable to indicate successful registration
        registration_successful = True
        message = MIMEMultipart()
        message['From'] = sender_email
        message['To'] = email
        message['Subject'] = "User Registration Successful"
                # Modify the email body string to include multiple lines
        body = "Congratulations!!! You are successfully added to Opcenter Team.\n\n"
        body += "Kindly save the following information:\n"
        body += "Email: " + email + "\n"
        body += "Password: " + password + "\n\n"
        body += "This information is confidential and should not be shared with anyone."
        message.attach(MIMEText(body, 'plain'))
        
        body += "Visit https://www.opcenterv2.parablu.com"
        # Create a SMTP session
        smtp_session = smtplib.SMTP(smtp_server, smtp_port)
        smtp_session.starttls() # Secure the connection

        # Login with credentials
        smtp_session.login('AKIAVZLS53X5PBNLV5GJ', 'BLPn8AcrtZTJz+BdyyTCccNQqj6UxIB/kvKMv9AWd/mB')

        # Send the message via the SMTP server
        smtp_session.sendmail(sender_email, email, message.as_string())

        # Terminate the SMTP session
        smtp_session.quit()
        print("The Mail Sent Successfully!!!")
        # Render the profile page with the success message
        return redirect(url_for('admin.deleted_users', registration_successful=registration_successful))
        # return render_template('dashboard/deleteUsers.html', registration_successful=registration_successful,users = usersInList)
    # If the request method is GET, render the registration form
    return redirect(url_for('admin.deleted_users', users = usersInList))
    # return render_template('dashboard/deleteUsers.html',users = usersInList)

#The Below one is for the Licence page
@is_logged_in
@admin.route("/chooselicenceModal",methods=['GET','POST'])
def chooselicenceModal():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    details = {}
    if request.method == 'POST':
        userid = request.form['userid']
        print("The User Id is "+ userid)

        licence = LicenceData.find_one({'cloudName':userid},sort=[('_id', pymongo.DESCENDING)])
        print("It is coming to this line 1160")
        # for i in licence:
        cloudName = licence.get("cloudName")
        details.update({'Cloud Name': cloudName})
        print("It is coming to this line 1164")
        nosOfMiniCloud = int(float(licence.get('noOfMiniCloudsAllowed')))
        print("It is coming to this line 1166")
        details.update({'Total Number of Miniclouds': nosOfMiniCloud})
        cloudSizeAllowed = int(float(licence.get("cloudSizeAllowed")))
        print("It is coming to this line 1169")
        cloudSize = int(float(cloudSizeAllowed/1024))
        
        details.update({'Cloud Size Allowed': str(cloudSize)+" GB"})
        nosOfSyncUsers = int(float(licence.get("noOfSyncUsersAllowed")))
        print("It is coming to this line 1174")
        details.update({'Number of Sync Users allowed': nosOfSyncUsers})
        nosOfBackupUsers = int(float(licence.get("noOfBackupUsersAllowed")))
        print("It is coming to this line 1177")
        details.update({'Number of Backup Users allowed': nosOfBackupUsers})

        nosOfOnedriveDevice = int(float(licence.get("noOfOneDriveUsersAllowed")))
        print("It is coming to this line 1181")
        details.update({'Number of OneDrive Users allowed': nosOfOnedriveDevice})

        nosOfExchange = int(float(licence.get("noOfExchangeUsersAllowed")))
        print("It is coming to this line 1185")
        details.update({'Number of Exchange Users allowed': nosOfExchange})
        contentSearchEnabled = int(float(licence.get("contentSearchEnabled")))
        print("It is coming to this line 1188")
        if(contentSearchEnabled):
            details.update({'Content Search is': "Enabled"})
        else:
            details.update({'Content Search is': "Disabled"})

        versionEnabling = int(float(licence.get("versioningEnabled")))
        print("It is coming to this line 1195")
        details.update({'Version Enabling': versionEnabling})
        statusCode = licence.get("statusCode")
        print("It is coming to this line 1198")
        details.update({'Status Code': statusCode})
        cloudId = int(float(licence.get("cloudId")))
        print("It is coming to this line 1201")
        details.update({'CloudId': cloudId})
        externalStorage = int(float(licence.get("externalStorageAllowed")))
        print("It is coming to this line 1204")
        details.update({'External Storage Allowed': externalStorage})
        enableMedia = int(float(licence.get("enableMedia")))
        print("It is coming to this line 1206")
        details.update({'Enable Media': enableMedia})
        LicenceKeyFileName = licence.get("licenseKeyFileName")
        print("It is coming to this line 1209")
        details.update({'Licence Key Filename': LicenceKeyFileName})
        try:
            updateFrequency = int(float(i["updateFrequency"]))
        except Exception:
               details.update({'Update Frequency': "N/A"})
        try:
            updateFrequency = int(float(i["graphAADEnabled"]))
        except Exception:
               details.update({'Graph AAD Enabled': "N/A"})
        
        print("It is coming to this line 1217")
        try:
            print("It is coming to this line 1219")
            multiTenantAADEnabled = int(float(licence.get("multiTenantAADEnabled")))
            print("It is coming to this line 1221")
            details.update({'Multi Tenant AAD Enabled': multiTenantAADEnabled})
        except Exception:
            print(Exception)
            details.update({'Multi Tenant AAD Enabled': "N/A"})

        try:
            mailRecoverableItemsEnabled = int(float(licence.get("mailRecoverableItemsEnabled")))
            if(mailRecoverableItemsEnabled):
                details.update({'Backup is for Recovery and Purge': "Enabled"})
            else:
                details.update({'Backup is for Recovery and Purge': "Disabled"})
        except Exception:
            details.update({'Backup is for Recovery and Purge': "N/A"})

        print("It is coming to this line 1232")

        noOfDevicesAllowed = int(float(licence.get("noOfDevicesAllowed")))
        details.update({'Number of Device Allowed': noOfDevicesAllowed})
        allowedDeviceOwnershipPer = int(float(licence.get("allowedDeviceOwnershipPer")))
        details.update({'Allowed Device Ownership per User': allowedDeviceOwnershipPer})
        noOfUsersAllowed = int(float(licence.get("noOfUsersAllowed")))
        details.update({'Number of Users Allowed': noOfUsersAllowed})   
        details.update({'License Details': "Click here"})  

    # print("The hostname is :" + hostname)
    return jsonify({'htmlresponse': render_template('dashboard/licenceData.html',employeelist = details,cloudName = cloudName)})



@is_logged_in
@admin.route("/color",methods=['GET','POST'])
def color():

    muxCount = 0

    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))
    
    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    # num =[]   
    if request.method == 'POST':
        userid = request.form['userid']
        my_logger.info("The userid for the ")
        my_logger.info(userid)
        my_logger.info("The UserId for the line 1672 is ============================================================================================")
        
        
        
        data = colors.find_one({'username':userid}, sort=[('_id', pymongo.DESCENDING)])
        if data is None:
            checkUserid = findHostNameWithSystem(userid)
            data = colors.find_one({'username':checkUserid}, sort=[('_id', pymongo.DESCENDING)])
            my_logger.info("The vakue of the data was None")
            my_logger.info(data)

    
        num = {}

        final_active = 0
        active_data = usersTotal.find_one({'Cloud Name': userid},sort=[('_id', pymongo.DESCENDING)])
        my_logger.info("The below is the active data : ")
        my_logger.info(active_data)
        try:
            if active_data is not None:
                active_user_with = active_data.get('Active_user_with_device')
                final_active = active_user_with.replace(",", "")
            else:
                final_active = 0
        except Exception:
            final_active = 0

        try:
            if data is not None:
                scorecard = data.get('scorecardHeard')
            else:
                scorecard = '0'
        except Exception:
            scorecard = '0'


        print("The scorecard value at line 196 is")
        print(scorecard)
        try:
            if(scorecard!='0'):
                score_value = int(scorecard[:-2].split('(')[1])
            else:
                score_value = 0
        except Exception:
            score_value = 0

        print(score_value)
        
        try:
            if data is not None:
                fullBackup = data.get('usersWithFirstBackup').replace(",","")
            else:
                fullBackup = 0
        except Exception:
            fullBackup = 0

        try:
            if data is not None:
                ActiveUsers = data.get('fullBackup').replace(",","")
            else:
                ActiveUsers = 0
        except Exception:
            ActiveUsers = 0

        print("printing active users")
        print(ActiveUsers)
        print("The value of the fullBackup is :" + str(fullBackup))

        try:
            if data is not None:
                MuxType = data.get('MuxType')
                if MuxType is None:
                    MuxType = 0
            else:
                MuxType = 0
        except Exception:
            MuxType = 0

        try:
            if data is not None:
                black202 = data.get('Black202')
                if black202 is None:
                    black202 = ''
                
            else:
                black202 = ''
        except Exception:
            black202 = ''

        length202 = len(black202)

        try:
            if data is not None:
                black404 = data.get('black404')
                if black404 is None:
                    black404 = ''
                
            else:
                black404 = ''
        except Exception:
            black404 = ''

        length404 = len(black404)
        
        validity = "N/A"


        try:
            if data is not None:
                device_proc = data.get('deviceProtected')
                if device_proc is None:
                    device_proc = '0'
                if device_proc != '0':
                    device_value = int(device_proc[:-2].split('(')[1])
                else:
                    device_value = 0
            else:
                device_value = 0
        except Exception:
            device_value = 0
        print("The value of the device_value is :" + str(device_value))


        try:
            if data is not None:
                oneDrive = data.get("onedriveStorage")
                lengthOne = 0
                if oneDrive is None or len(oneDrive) == 0:
                    lengthOne = 0
                else:
                    lengthOne = len(oneDrive)
            else:
                lengthOne = 0
                oneDrive = []
        except Exception:
            lengthOne = 0
            oneDrive = []
        
        num.update({"Devices had a heartbeat to the server in the last 30 days" : [str(score_value),"Greater than 70%",score_value]})
        AADExpiredOrNot = "N/A"
        try:
            my_logger.info("The value of Cloname")
            my_logger.info("===========================================================----------------------------------------------------------")
            my_logger.info(userid) 
            my_logger.info("-=--=-=-=-=-=-=-=-=-=-0---")
            dataprocListNew = dataprotectionList.find_one({'CloudName':userid}, sort=[('_id', pymongo.DESCENDING)])
            my_logger.info(dataprocListNew)
            my_logger.info("=================================================================================================")
            fullBackup = int(dataprocListNew.get("fullbackupCompleted").replace(",",""))
            my_logger.info(fullBackup)
            my_logger.info("================================================================================================")
            my_logger.info("The Value of full backup is mentioned above")
            atleastOneUser = int(dataprocListNew.get("atleastOneDevice").replace(",",""))
            my_logger.info("=======----------------------------------------------------++++++++++++++++++++++++++++++++++++++++++")
            my_logger.info(atleastOneUser)
            my_logger.info("CLOSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSE")
        
        
        except:
            fullBackup = 0
        try:
            my_logger.info("The value at 1848 is ")
            my_logger.info(atleastOneUser)
            if atleastOneUser != 0:
                percentageFullbackup = (fullBackup * 100) / atleastOneUser 
                my_logger.info(percentageFullbackup)
            else:
                percentageFullbackup = 0
        except Exception:
            percentageFullbackup = 0


 
        #num.update({"AAD Auth token expiry":[AADExpiredOrNot,"Should be Expired",AADExpiredOrNotColor]})

        num.update({"Full Backups Completed":[str(int(percentageFullbackup)),"Greater than 70%",percentageFullbackup]})

        num.update({"Devices have been protected in the last 30 days":[str(device_value),"Greater than 70%",device_value]})
            
        num.update({"Black List 201 Users":[black202,"Should be 0"]})
        
        num.update({"Black List 404 Users":[black404,"Should be 0"]})
        
        # Cloud = CloudName.find_one({'System Name': userid},sort=[('_id', pymongo.DESCENDING)])
        
        # cloudN =Cloud.get('CloudName')

        if(MuxType):
            MuxUsers = MuxDatauserList.find_one({"cloudName": userid},sort=[('_id', pymongo.DESCENDING)])
            muxValue = []
            if MuxUsers is not None:
                muxValue = MuxUsers.get('muxFileUsers')
            else:
                muxValue = []
            print("The below is the count of the mux users")
            if muxValue is not None:
                muxCount = len(muxValue)
            else:
                muxCount = 0
            if muxCount > 0:
                num.update({"Users with No Storage Buckets":[muxValue,"Should be 3"]})
        
                
        email_percentages = {}

        print("The value of userid is : "+ userid)

        licenceAdillllll = LicenceDataAddil.find_one({"cloudName":userid},sort=[('_id', pymongo.DESCENDING)])

        if licenceAdillllll is not None:
            LicenceArray = licenceAdillllll.get('LicenceAdditional')
        else:
            LicenceArray = []


        my_logger.info("The line number 1687")
        
        if(len(LicenceArray) > 0):
            my_logger.info("This is the line 1864")
            if "ODB Enabled" in LicenceArray:
                print("The below is the value of onedrive")
                my_logger.info("This is insode the ODB ENabled")
                if oneDrive is None:
                    OneDriveSize = 0
                    my_logger.info("This is OneDriveSize =0")
                    num.update({"Users OneDrive Storage Exceeded":[OneDriveSize,"Should be 0"]})
                else:
                    if(len(oneDrive) != 0):
                        for email in oneDrive:
                            parts = email.split('|')
                            email_percentages[parts[0]] = round(float(parts[1]), 2)
                    
                    print("The Below is the email Percentages")
                    print(email_percentages)
                    OneDriveSize = len(email_percentages)

                    num.update({"Users OneDrive Storage Exceeded":[OneDriveSize,"Should be 0"]})

       
        my_logger.info("I am in line 1895")
        try: 
            try:
                if data is not None:
                    my_logger.info("---------------------------------------------------------------------------------------------------------------------")
                    LicenceValidity = data.get('validity')
                    my_logger.info("The value of the validity at line 915 is ")
                    my_logger.info(LicenceValidity)
                    my_logger.info("-----------------------------------------------------------------------------------------------------------------------")


                    if LicenceValidity is None:
                        my_logger.info("The value is entering here 1905")
                        LicenceValidity = 'N/A'
            except Exception:
                LicenceValidity = 'N/A'

            my_logger.info("The validity: "+ LicenceValidity)
            
            my_logger.info("This is line 1885")
            format = "%d %b %Y %H:%M:%S"
            my_logger.info("This is after format")
            my_logger.info("I am in line 1898")
            my_logger.info("The valididty : " +LicenceValidity)
            my_logger.info("===========================================")
            if LicenceValidity != "N/A" or LicenceValidity != "" or LicenceValidity is not None:
                date_object = datetime.strptime(LicenceValidity, format)
                my_logger.info("The date bjet is ")
                my_logger.info(date_object)
                my_logger.info("This is line 1888")

                millisec = int(date_object.timestamp() * 1000)
                my_logger.info("This is line 1891")
                obj = time.gmtime(0)
                epoch = time.asctime(obj)
                curr_time = round(time.time()*1000)
                my_logger.info("Milliseconds since epoch:",curr_time)

                my_logger.info("This is line number 1896")
                print("MilliSecods=", millisec)
                period =  millisec -curr_time 
                print(period)
        # if(period<604800000):
                num.update({"License Validity": [LicenceValidity,"> 7 Days"]})
            else:
                my_logger.info("The validity is empty")
                num.update({"License Validity": ["N/A","> 7 Days"]})
        # if(validity):
        #     num.update({"validity":"The licence ends on "+validity})
        except:
            num.update({"License Validity":[0,"> 7 Days"]})


        try:
            SystemName = findHostNameWithSystem(userid)
            my_logger.info("The value if the SystemName is "+SystemName)

            databaseName = "cloud_"+userid
            

            my_logger.info("The valie of the databasename is : "+ databaseName)
            systemCollection = dbs[databaseName]

            systemView = systemCollection.find_one({'System Name':SystemName},sort=[("Date & Time ",pymongo.DESCENDING)])
            my_logger.info("The below is the document from the collection")
            my_logger.info(systemView)

            try:
                lastMongoBackup = systemView.get("lastMongoUpdate")
                my_logger.info("The last MongoBackup is: "+ lastMongoBackup)
                if(lastMongoBackup is not None or lastMongoBackup != "N/A" or lastMongoBackup != "0" or lastMongoBackup != 0):
                    lastMongoBackup = convert_to_ist(lastMongoBackup)
                    recordedDate = systemView.get('Date & Time ')
                    recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                    recordedDate = recordedDate.strftime("%b %d %Y %H:%M")
                    my_logger.info("Tje return result value is : ")
                    date = lastMongoBackup.replace('IST', '+0530')
                    date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                    formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')
                    mongoColor = compareDateWithDays(recordedDate,formatted_date2,3)
                    my_logger.info("Tje return result value is : ")
                
                else:
                    mongoColor = "red"

                
                num.update({"Last Mongo Backup":[lastMongoBackup,"Date & Time :",mongoColor]})

            except Exception as e:
                my_logger.info(e)
                my_logger.info("The value of exception is above")
                mongoColor = "red"
                num.update({"Last Mongo Backup":["N/A","Date & Time :",mongoColor]})


            try:
                lastnightyrestart = systemView.get("lastNightlyRestart")
                if(lastnightyrestart != "-" or lastnightyrestart is not None or lastnightyrestart != "N/A"):
                    
                    recordedDate = systemView.get('Date & Time ')
                    recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                    recordedDate = recordedDate.strftime("%b %d %Y %H:%M")
                    my_logger.info("Tje return result value is : ")

                    lastnightyrestart = convert_to_ist(lastnightyrestart)
                    date = lastnightyrestart.replace('IST', '+0530')
                    date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                    formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')


                    nightColor = compareDateWithDays(recordedDate,formatted_date2,1)

                else:
                    nightColor = "red"
                
                num.update({"Last Nightly Restart":[lastnightyrestart,"Date & Time :",nightColor]})

            except Exception as e:
                my_logger.info(e)
                nightColor = "red"
                num.update({"Last Nightly Restart":["N/A","Date & Time :",nightColor]})
                my_logger.info("The value of exception is above")


            try:
                physicalMemory = systemView.get("Total Physical Memory")
                usedMemory = systemView.get("Used Physical Memory")
                if((physicalMemory != "-" or physicalMemory is not None or physicalMemory != "N/A") and (usedMemory != "-" or usedMemory is not None or usedMemory != "N/A")):
                    # result = compareDate(lastMongoBackup,1)
                    my_logger.info("The value of the total physical memory is : " + physicalMemory)
                    my_logger.info("The value of the used physical memory is : " + usedMemory)

                    try:
                        finalPercentage = (int(usedMemory) * 100)/int(physicalMemory)
                    except Exception:
                        finalPercentage = 0


                    my_logger.info("The percentager of the used memory is : ")
                    my_logger.info(finalPercentage)
                    if finalPercentage > 90:
                        phyStatus = "red"
                    else:
                        phyStatus = "green"
                
                else:
                    physicalMemory = "N/A"
                    phyStatus = "red"

                my_logger.info("The value of the ram size in the round of method")
                my_logger.info(finalPercentage)
                
                num.update({"RAM Size":[finalPercentage,"Exceeds 90% :",phyStatus]})


            except Exception as e:
                my_logger.info(e)
                my_logger.info("The value of exception is above")   
                num.update({"Ram Size":["N/A","Exceeds 90% :","red"]})


            try:
                WireTigerSize = systemView.get("WireTigerSize")
                wireTigerSize = WireTigerSize.split()
                wireTigerSizeinBytes = int(wireTigerSize[0])

                my_logger.info("The alue of the wireTigerSize in bytes is : ")
                my_logger.info(wireTigerSizeinBytes)

                gb_value = wireTigerSizeinBytes / (1024 * 1024 * 1024)

                if gb_value > 20:
                    status = "red"
                else:
                    status = "green"

                num.update({"WiredTiger Cache Size":[str(round(gb_value,2))+" GB","Exceeds 20 GB :",status]})


            except Exception as e:
                my_logger.info(e)
                num.update({"WireTigerSize":["N/A","Exceeds 20% :","red"]})


            try:
                uploadFileSizeLimit = systemView.get('uploadFileSizeLimitInMB')
                my_logger.info("The upload file size limit is ")
                my_logger.info(uploadFileSizeLimit)
                if(int(uploadFileSizeLimit) < 5):
                    uploadFileSizeLimitColor = "darkgreen"
                else:
                    uploadFileSizeLimitColor = "red"
            
                num.update({"File Upload Size Limit":[uploadFileSizeLimit + " MB","Exceeds 4 MB :",uploadFileSizeLimitColor]})

            except Exception:
                num.update({"File Upload Size Limit":["N/A","Exceeded 20% :","red"]})



            try:
                moreDetails.update({'Parablu Disk Mounted':[systemView.get('parabluDiskMounted')]})
                parabluMounted = systemView.get('parabluDiskMounted')
            except Exception:
                parabluMounted = "Not Mounted"
                


            my_logger.info("=================================Parablu Disk Details===========================================")
            
            
            try:
                my_logger.info("The line number 2383")
                my_logger.info(systemView.get('parabluSize'))
                parabluDiskSize = systemView.get('parabluSize')
                if parabluDiskSize is not None:
                    my_logger.info("The line number 2384" + parabluDiskSize)
                    my_logger.info("The line number 2384")
                    parabluDiskBytes = convert_to_bytes(systemView.get('parabluSize'))
                    my_logger.info(parabluDiskBytes)
                    my_logger.info("The line number 2385")
                    my_logger.info(int(parabluDiskBytes))
                else:
                    parabluDiskBytes = convert_to_bytes2(systemView.get('Total Space'))
                    my_logger.info("The line number 2395")
            except Exception:
                my_logger.info("The line number 2388")
                parabluDiskBytes = 0
                parabluDiskSize = "N/A"
            
            
            try:
                if parabluMounted == "Not Mounted" or parabluDiskSize == "N/A" or parabluDiskSize is None:
                    my_logger.info("The line number 2395")
                    parabluDiskBytes = convert_to_bytes2(systemView.get('Total Space'))
                    my_logger.info("The parablu disk is not mounted so considering / value")
                    my_logger.info("The vlue oif the / parablu is :")
                    my_logger.info(parabluDiskBytes)

            except:
                my_logger.info("The line number 2402")
                parabluDiskBytes = 0

          
            try:
                
                my_logger.info("The valie of yje line 2884 is ")
                #my_logger.info(tmpChunckFolderSize)
                tmpChunkFolderBytes = convert_to_bytes(systemView.get('tmpFolder'))
                my_logger.info("the value of the tmpchunk folder in byters")
                my_logger.info(tmpChunkFolderBytes)
            except Exception:
                tmpChunkFolderBytes = 0
                #tmpChunckFolderSize = 0
        
            
            try:
                percentagetmpChunk = (int(tmpChunkFolderBytes) * 100)/int(parabluDiskBytes)
                my_logger.info("The valiue ay the line number 2491 is ")
                my_logger.info(percentagetmpChunk)
            except:
                percentagetmpChunk = 0


            if(percentagetmpChunk > config.percentagetmpChunk):
                tmpChunkColor = "red"
            else:
                tmpChunkColor = "green"


            try:
                tmpChunkFolderBytes = int(tmpChunkFolderBytes)/1024
                tmpChunkFolderBytes = tmpChunkFolderBytes /1024
                tmpChunkFolderBytes = tmpChunkFolderBytes /1024
            except Exception:
                tmpChunkFolderBytes = 0

            num.update({"/tmp-chunk folder size":[tmpChunkFolderBytes,"Exceeds 25% :",tmpChunkColor]})


            try:
                patchfileSize = systemView.get('patchFileSize')+"B"
                patchfileSizeBytes = convert_to_bytes(systemView.get('patchFileSize'))
                my_logger.info("The Paych file iuze oid : ")
                my_logger.info(patchfileSizeBytes)
            except Exception:
                my_logger.info("This is the exception : ")
                patchfileSizeBytes = 0

            
            
            if(patchfileSizeBytes <= config.patchfileSizeBytes):
                patchfileSizeColor = "green"
            else:
                patchfileSizeColor = "red"



            num.update({"/patch folder size":[patchfileSize,"Exceeds 40 GB :",patchfileSizeColor]})
            

            backupStatus = "green"
            try:
                syncFolder = systemView.get('SyncFolderSize') +"B"
                syncFolderBytes = convert_to_bytes(systemView.get('SyncFolderSize'))
                my_logger.info("The Sync folder Bytes is : ")
                my_logger.info(syncFolderBytes)

            except Exception:
                syncFolder = "0"
                syncFolderBytes = 0

            if(syncFolderBytes <= 8192):
                syncFolderColor = "green"
            else:
                syncFolderColor = "red"

            
            num.update({"/sync-upload folder size":[syncFolder,"Exceeds 8 KB :",syncFolderColor]})
            

            
            try:
                backupPolicy = systemView.get('BackupPolicy')
                backupPolicy = backupPolicy.capitalize()
            except Exception:
                backupPolicy = "N/A"

            my_logger.info("===================================LINE 2923==============================================================")

            my_logger.info(backupPolicy)
            my_logger.info("===================================LINE 2925==============================================================")

            if(backupPolicy != "Enabled"):
                backupStatus = "red"
            else:
                backupStatus = "green"

            # num.update({"Dedup Backup Policy":[backupPolicy,"Disabled :",backupStatus]})
            
            try:
                swapSpace = systemView.get('Swap Memory / Disabled')
                finalSwapSpace = int(swapSpace) /1024
                my_logger.info("The value of the swap space is : ")
                my_logger.info(swapSpace)
            except Exception:
                swapSpace = 0

            if(int(swapSpace) > int(physicalMemory) * 2):
                swapColor = "green"
            else:
                swapColor = "red"

            num.update({"Swap Space":[str(round(finalSwapSpace,2)) + "GB"," Should be twice the RAM :",swapColor]})


            
        
        except Exception as e:
            my_logger.info(e)
            my_logger.info("The value of exception is above")
            num.update({"Last Mongo Backup on":["N/A","Date&Time :","red"]})
            num.update({"Last Nightly Restart on":["N/A","Date&Time :","red"]})
            num.update({"Ram Size":["N/A","Exceeded 90% :","red"]})
            num.update({"/upload folder size":["N/A","Exceeded 35% :","red"]})
            num.update({"/tmp-chunk folder size":["N/A","Exceeded 25% :","red"]})



        # num.update({"AAD Auth token expiry":[AADExpiredOrNot,"Should be Active",AADExpiredOrNotColor]})



        #This is the line where I will see all the storage buckets 

        # userid
        my_logger.info("================================LINE 2973========================================================================")
        my_logger.info("The value of the User Id is : ")
        my_logger.info(userid)


        licenceAdillllll = LicenceDataAddil.find_one({'cloudName':userid}, sort=[('_id', pymongo.DESCENDING)])
        LicenceArray = licenceAdillllll.get('LicenceAdditional')
        my_logger.info("=================================LINE 2976=======================================================================")
        

        uniqueCount = 0
        # try:
        #     if "ODB Enabled" in LicenceArray:
        #         dataprocListNew = dataprotectionList.find_one({'CloudName':userid}, sort=[('_id', pymongo.DESCENDING)])

        #         my_logger.info("The value of the data protectection list is ")
        #         my_logger.info(dataprocListNew)

        #         if dataprocListNew is not None:
        #             typeOfOdbDetails = dataprocListNew.get('MUX-MIX')
        #             my_logger.info("The value of yje type of details is ")
        #             my_logger.info(typeOfOdbDetails)

        #             if typeOfOdbDetails is not None:
        #                 if typeOfOdbDetails == "MUX":
        #                     value = True
        #                 elif typeOfOdbDetails == "MIX":
        #                     value = True
        #                 elif typeOfOdbDetails == "NON-MUX":
        #                     value = True

        #                 else:
        #                     value = False

        #             else:
        #                 latest_active_data = usersTotal.find_one({'Cloud Name': userid}, sort=[('_id', pymongo.DESCENDING)])
        #                 Muxdatas = colors.find_one({'username':userid}, sort=[('_id', pymongo.DESCENDING)])
                        
        #                 if Muxdatas is None:
        #                     clientName = findHostNameWithSystem(userid)
        #                     Muxdatas = colors.find_one({'username':clientName}, sort=[('_id', pymongo.DESCENDING)])

        #                 if(Muxdatas.get('MuxType')):
        #                     value = Muxdatas.get('MuxType')    
        #                 else:
        #                     value = Muxdatas.get('MuxType')

        #         else:
        #             latest_active_data = usersTotal.find_one({'Cloud Name': userid}, sort=[('_id', pymongo.DESCENDING)])
        #             Muxdatas = colors.find_one({'username':userid}, sort=[('_id', pymongo.DESCENDING)])
                    
        #             if Muxdatas is None:
        #                 clientName = findHostNameWithSystem(userid)
        #                 Muxdatas = colors.find_one({'username':clientName}, sort=[('_id', pymongo.DESCENDING)])

        #             if(Muxdatas.get('MuxType')):
        #                 value = Muxdatas.get('MuxType')    
        #             else:
        #                 value = Muxdatas.get('MuxType')

            
        #     if(value):  
        #         my_logger.info("This value is true")
        #         my_logger.info("They are either Mux or Mix based one drive")
        #         latest_active_data = usersTotal.find_one({'Cloud Name': userid}, sort=[('_id', pymongo.DESCENDING)])
        #         addCloudPrefixMux = "cloud_"+userid+"mux"
        #         my_logger.info("The value of the addCloudPrefixMux at line 3042 is: " + addCloudPrefixMux)
        #         if addCloudPrefixMux in dbs.list_collection_names():
        #             myMachineMuxCollection = dbs[addCloudPrefixMux]
        #         else:
        #             clientMux = findHostNameWithSystem(client)
        #             addCloudPrefixMux = "cloud_"+clientMux+"mux"

        #         myMachineMuxCollection = dbs[addCloudPrefixMux]
                
        #         unique_odbLoginIds = myMachineMuxCollection.distinct('odbLoginId')
        #         my_logger.info("I am in the line 3052")

        #         my_logger.info("The below is the size of the Unique Id's : ")
        #         my_logger.info(len(unique_odbLoginIds))
        #         uniqueIdLength = len(unique_odbLoginIds)
                

        #         for odbLoginId in unique_odbLoginIds:
        #             document = myMachineMuxCollection.find_one({'odbLoginId': odbLoginId},sort=[('DateTime', pymongo.DESCENDING)])
        #             my_logger.info(document)
        #             if document is not None:
        #                 my_logger.info("The value of the percentage is ")
        #                 percentage = document['Details']['percentage']
        #                 my_logger.info(percentage)
        #                 if(int(percentage) > 90):
        #                     uniqueCount = uniqueCount + 1





        #         my_logger.info("============3059==================")

        #     my_logger.info("the value of buckets which exceeded the 50 percentage is ")
        #     my_logger.info(uniqueCount)
        # except Exception as e:
        #     my_logger.info(e)
        #     my_logger.info("I am in Exception ")


        # if uniqueCount > 0:
        #     uniqueCountColor = "red"
        #     uniqueCo = uniqueCount
        # else:
        #     uniqueCountColor = "darkgreen"
        #     uniqueCo = "No Buckets"

        # num.update({"Users storage buckets exceeds limit":[uniqueCo,"Should exceeds the limit",uniqueCountColor]})
        
        
    # print(len(num))
    return jsonify({'htmlresponse': render_template('dashboard/response.html',period = period,employeelist=num,client = userid,muxCount = muxCount,length202=length202,length404=length404,lengthOne = lengthOne)})





@is_logged_in
@admin.route("/blackfour",methods=['GET','POST'])
def blackfourzerofour():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        data = colors.find_one({'username':userid},sort=[('_id', pymongo.DESCENDING)])
        if data is None:
            clientName = findHostNameWithSystem(userid)
            my_logger.info("The value of the clientName in linme 2127"+clientName)
            data = colors.find_one({'username':clientName},sort=[('_id', pymongo.DESCENDING)])
            my_logger.info("The value of data in line 2132 is ")
            my_logger.info(data)
        
        black404 = data.get('black404')

        # for j in black404:
        #     print(j)
    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = black404)})


@admin.route("/onedriveStorage",methods=['GET','POST'])
def onedriveStorage():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    email_percentages = {}
    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        print("The line number 1729")

        data = colors.find_one({'username':userid}, sort=[('_id', pymongo.DESCENDING)])
        if data is None:
            clientName = findHostNameWithSystem(userid)
            my_logger.info("The value of the clientName in linme 2127"+clientName)
            data = colors.find_one({'username':clientName},sort=[('_id', pymongo.DESCENDING)])


        if data is not None:
            oneDrive = data.get("onedriveStorage")
            lengthOne = 0
            if oneDrive is None or len(oneDrive) == 0:
                lengthOne = 0
            else:
                lengthOne = len(oneDrive)
        else:
            lengthOne = 0
            oneDrive = []


        #print("The value of userid is : "+ cloudN
        my_logger.info("=======================================================================================================")
        licenceAdillllll = LicenceDataAddil.find_one({"cloudName":userid},sort=[('_id', pymongo.DESCENDING)])

        my_logger.info(licenceAdillllll)
        my_logger.info("=======================================================================================================")
        

        if licenceAdillllll is not None:
            LicenceArray = licenceAdillllll.get('LicenceAdditional')
        else:
            LicenceArray = []
        
        if(len(LicenceArray) > 0):
            if "ODB Enabled" in LicenceArray:
                print("The below is the value of onedrive")
                my_logger.info("I am inside in the line 2189--------------------------------=================================")
                if oneDrive is None:
                    OneDriveSize = 0
                    num.update({"Users Onedrive Storage Exceeded":[OneDriveSize,"Should be 0"]})
                else:
                    if(len(oneDrive) != 0):
                        for email in oneDrive:
                            parts = email.split('|')
                            email_percentages[parts[0]] = round(float(parts[1]), 2)
                    
                    my_logger.info("The Below is the email Percentages")
                    my_logger.info(email_percentages)
        for key,value in email_percentages.items():
            my_logger.info(key)
            my_logger.info("-------------------------------------------------------------------------------------------------------")
            my_logger.info(value)


    return jsonify({'htmlresponse': render_template('dashboard/ondriveEmail.html',email_perc = email_percentages)})
 #   return jsonify(email_percentages)

@is_logged_in
@admin.route("/StorageBuckets",methods=['GET','POST'])
def storageBuckets():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    if request.method == 'POST':
        userid = request.form['userid']
        # for mux in Cloud:
        MuxUsers = MuxDatauserList.find_one({"cloudName": userid},sort=[('_id', pymongo.DESCENDING)])
        # for muxUse in MuxUsers:
        muxValue = MuxUsers.get('muxFileUsers')
        print("The below is the count of the mux users")
        print(len(muxValue))
        # for j in black404:
        #     print(j)
    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = muxValue)})




@is_logged_in
@admin.route("/blacktwo",methods=['GET','POST'])
def blacktwozerotwo():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if request.method == 'POST':
        userid = request.form['userid']

        my_logger.info("This is line 2121")
        my_logger.info("The value of the userid is "+userid)
        print(userid)
        data = colors.find_one({'username':userid},sort=[('_id', pymongo.DESCENDING)])
        my_logger.info("The value of the data is")
        my_logger.info(data)
        if data is None:
            clientName = findHostNameWithSystem(userid)
            my_logger.info("The value of the clientName in linme 2127"+clientName)
            data = colors.find_one({'username':clientName},sort=[('_id', pymongo.DESCENDING)])
            my_logger.info("The value of data in line 2132 is ")
            my_logger.info(data)
        #for i in data:
         #   black202 = i['Black202']

        black202 = data.get('Black202')
        my_logger.info("The Belowis black 202 data")
        my_logger.info(black202)

        # for j in black404:
        #     print(j)
    return jsonify({'htmlresponse': render_template('dashboard/blacktwo.html',black202 = black202)})


def convert_to_bytes(size):
    my_logger.info("The valie of the size inside the convert to bytes is")
    my_logger.info(size)
    if size[-1].upper() == 'G':
        bytes_value = int(float(size[:-1])) * 1024**3
    elif size[-1].upper() == 'M':
        bytes_value = int(float(size[:-1])) * 1024**2
    elif size[-1].upper() == 'K':
        bytes_value = int(float(size[:-1])) * 1024
    else:
        bytes_value = int(size)
    return bytes_value



def convert_to_bytes2(size):
    # Split the string into value and unit
    my_logger.info("The value of the size_parts ")
    my_logger.info(size)
    size_parts = size.split()
    my_logger.info("The value of the size_parts ")
    my_logger.info(size_parts)

    value = float(size_parts[0])
    unit = size_parts[1]

    # Define the conversion factors
    unit_conversion = {
        'B': 1,
        'KB': 1024,
        'MB': 1024**2,
        'GB': 1024**3,
        'TB': 1024**4,
        'K': 1024,
        'G': 1024**3,
        'M': 1024**2
    }

    # Convert the value to bytes
    bytes_value = value * unit_conversion[unit]

    return bytes_value

@is_logged_in
@admin.route("/uptime",methods=['GET','POST'])
def uptimedetails():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    System = {}
    Apache = {}
    Mongo = {}
    Tomcat = {}
    news = {}
    rams = {}
    physical = {}
    moreDetails = {}
    if request.method == 'POST':
        userid = request.form['userid']
        res = request.form['res']
        print(userid)
        print("The Value of res is here")
        print(res)
        resValue = res.partition(".parablu.com")[0]
        # addCloudPrefix = "cloud_"+res
        addCloudPrefix = "cloud_"+resValue
        mycollection=dbs[addCloudPrefix]
        cursor = mycollection.find({"System Name":userid})
        insideList = [] 
        for i in cursor:
            if i['System Name'] in insideList:
                continue
            else:
                insideList.append(i['System Name'])

        

        insideListCursor = []
        for i in insideList:
            cursorFinal = mycollection.find_one({'System Name':i},sort=[('_id', pymongo.DESCENDING)])

            my_logger.info("The System Name is  :")
            my_logger.info(i)
            my_logger.info(cursorFinal)
            # for j in cursorFinal:
            # insideListCursor.append(cursorFinal.get('cronUptime'))
            try:
                Mongo.update({'Mongo Version':[cursorFinal.get('Mongo Version')]})
            except Exception:
                Mongo.update({'Mongo Version':["0"]})
        
            my_logger.info("=====================================================================================================")
            try:
                mongoLastBackup = cursorFinal.get('lastMongoUpdate')
                if mongoLastBackup is not None or mongoLastBackup != "N/A" or mongoLastBackup != "0" or mongoLastBackup != 0:
                    my_logger.info("The value of the Mongo restart us ")
                    my_logger.info(mongoLastBackup)

                    recordedDate = cursorFinal.get('Date & Time ')
                    recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                    recordedDate = recordedDate.strftime("%b %d %Y %H:%M")


                    date = mongoLastBackup.replace('IST', '+0530')
                    date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                    formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')

                    mongoLastBackupColor = compareDateWithDays(recordedDate,formatted_date2,3)

                else:
                    my_logger.info("I am in the line 2460")
                    mongoLastBackupColor = "red"
                Mongo.update({'Mongo Last Backup':[cursorFinal.get('lastMongoUpdate'),mongoLastBackupColor]})
            except Exception:
                mongoLastBackupColor = "red"
                my_logger.info("I am in the line Exceptiom")

                Mongo.update({'Mongo Last Backup':["0",mongoLastBackupColor]})
            my_logger.info("=====================================================================================================")
        

            try:
                System.update({'System Name':[cursorFinal.get('System Name')]})
            except Exception:
                System.update({'System Name':["0"]})

            try:
                Apache.update({'Apache2 Uptime':[cursorFinal.get('Apache2Uptime')]})
            except Exception:
                Apache.update({'Apache2 Uptime':["0"]})
            

            try:
                Tomcat.update({'Tomcat PCB 1 Uptime':[cursorFinal.get('tomcatpcb1Uptime')]})
            except Exception:
                Tomcat.update({'Tomcat PCB 1 Uptime':["0"]})

            try:
                Tomcat.update({'Tomcat JOB 1 Uptime':[cursorFinal.get('tomcatjob11Uptime')]})
            except Exception:
                Tomcat.update({'Tomcat JOB 1 Uptime':["0"]})

            
            try:
                news.update({'Memcached Uptime':[cursorFinal.get('memcachedUptime')]})
            except Exception:
                news.update({'Memcached Uptime':["0"]})
            
            try:
                System.update({'Cron Uptime':[cursorFinal.get('cronUptime')]})
            except Exception:
                System.update({'Cron Uptime':["0"]})
            
            try:
                Mongo.update({'Mongo Uptime':[cursorFinal.get('mongodUptime')]})
            except Exception:
                Mongo.update({'Mongo Uptime':["0"]})
            
            
            try:
                System.update({'System Uptime':[cursorFinal.get('SystemUptime')]})
            except Exception:
                System.update({'System Uptime':["0"]})

            my_logger.info("=========================================THIS IS line 3662==================================================")

            try:
                wiretigerSize = cursorFinal.get('WireTigerSize')
                my_logger.info("The value of the Wire Tigwr siuze is ")
                my_logger.info(wiretigerSize)
                wireTigerSize = wiretigerSize.split()
                my_logger.info("The value of the Wire Tigwr siuze is  LINE 3667")
                my_logger.info(wireTigerSize)
                wireTigerSizeinBytes = int(wireTigerSize[0])
                my_logger.info("The value of the Wire Tigwr siuze is  LINE 3670")
                my_logger.info(wireTigerSizeinBytes)
                my_logger.info("The alue of the wireTigerSize in bytes is : ")
                my_logger.info(wireTigerSizeinBytes)

                gb_value = "0 bytes"
                bytes_value = wireTigerSizeinBytes
                color_value =  wireTigerSizeinBytes /(1024 * 1024 * 1024)
                if bytes_value < 1024:
                    gb_value = str(bytes_value) +" bytes"
                    
                elif bytes_value < 1024 * 1024:
                    gb_value = f"{bytes_value / 1024:.2f} KB"
                 
                elif bytes_value < 1024 * 1024 * 1024:
                    gb_value = f"{bytes_value / (1024 * 1024):.2f} MB"
                else:
                    gb_value = f"{bytes_value / (1024 * 1024 * 1024):.2f} GB"
                my_logger.info("------------------========================THIS IS LINE 3678==================================-----------------------------")

                my_logger.info(gb_value)
                if color_value > 20:
                    status = "red"
                else:
                    status = "green"

                my_logger.info(status)


                #finalGBvalue = str(round(gb_value,2))
                #my_logger.info(finalGBvalue)

                my_logger.info("------------------========================THIS IS LINE 3684==================================-----------------------------")

                Mongo.update({'WiredTiger cache space':[gb_value,status]})
            except Exception as e:
                my_logger.info(e)
                my_logger.info("=========================================THIS IS line 3693==================================================")
                Mongo.update({'WiredTiger cache space':["N/A","red"]})
            
            my_logger.info("The System Name is  :1779")
            
            try:
                Tomcat.update({'Incoming Thread Set':[cursorFinal.get('IncomingThread')]})
            except Exception:
                Tomcat.update({'Incoming Thread Set':["0"]})
            
            try:
                Tomcat.update({'Incoming Utilized':[cursorFinal.get('IncomingUtilized')]})
            except Exception:
                Tomcat.update({'Incoming Utilized':["0"]})
            

            try:
                Tomcat.update({'Outgoing Thread Set':[cursorFinal.get('OutgoingThread')]})
            except Exception:
                Tomcat.update({'Outgoing Thread Set':["0"]})
            
            my_logger.info("The System Name is  :1784")
            try:
                Apache.update({'Minimum Spare Server':[cursorFinal.get('minSpareServer')]})
            except Exception:
                Apache.update({'Minimum Spare Server':["0"]})
            
            try:
                Apache.update({'Maximum Spare Server':[cursorFinal.get('maxSpareServer')]})
            except Exception:
                Apache.update({'Maximum Spare Server':["0"]})
            
            try:
                Apache.update({'Maximum Request Workers':[cursorFinal.get('MaxRequestWorkers')]})
            except Exception:
                Apache.update({'Maximum Request Workers':["0"]})
            

            try:
                Apache.update({'Maximum Connections Per Child':[cursorFinal.get('MaxConnectionsPerChild')]})
            except Exception:
                Apache.update({'Maximum Connections Per Child':["0"]})
            
            try:
                Apache.update({'Maximum Clients':[cursorFinal.get('MaxClients')]})
            except Exception:
                Apache.update({'Maximum Clients':["0"]})
            

            try:
                Apache.update({'Server Limit':[cursorFinal.get('ServerLimit')]})
            except Exception:
                Apache.update({'Server Limit':["0"]})
            
            my_logger.info("The System Name is  :1791")
            try:
                moreDetails.update({'System Name':[cursorFinal.get('System Name')]})
            except Exception:
                moreDetails.update({'System Name':["0"]})
            

            try:
                moreDetails.update({'Parablu Disk Mounted':[cursorFinal.get('parabluDiskMounted')]})
                parabluMounted = cursorFinal.get('parabluDiskMounted')
            except Exception:
                parabluMounted = "Not Mounted"
                moreDetails.update({'Parablu Disk Mounted':["N/A"]})


            my_logger.info("=================================Parablu Disk Details===========================================")
            
            
            try:
                my_logger.info("The line number 2383")
                my_logger.info(cursorFinal.get('parabluSize'))
                parabluDiskSize = cursorFinal.get('parabluSize')
                if parabluDiskSize is not None:
                    my_logger.info("The line number 2384" + parabluDiskSize)
                    my_logger.info("The line number 2384")
                    parabluDiskBytes = convert_to_bytes(cursorFinal.get('parabluSize'))
                    my_logger.info(parabluDiskBytes)
                    my_logger.info("The line number 2385")
                    my_logger.info(int(parabluDiskBytes))
                else:
                    parabluDiskBytes = convert_to_bytes2(cursorFinal.get('Total Space'))
                    my_logger.info("The line number 2395")
            except Exception:
                my_logger.info("The line number 2388")
                parabluDiskBytes = 0
                parabluDiskSize = "N/A"

            if parabluDiskSize is None:
                parabluDiskSize = "N/A"
            
            moreDetails.update({'/parablu Size':[parabluDiskSize]})
            
            try:
                if parabluMounted == "Not Mounted" or parabluDiskSize == "N/A":
                    parabluDiskBytes = convert_to_bytes2(cursorFinal.get('Total Space'))
                    my_logger.info("The parablu disk is not mounted so considering / value")
                    my_logger.info("The vlue oif the / parablu is :")
                    my_logger.info(parabluDiskBytes)

            except:
                parabluDiskBytes = 0
            
            try:
                parabluDiskUsage = cursorFinal.get('parabluUsed')+"B"
                # parabluDiskBytes = convert_to_bytes(cursorFinal.get('parabluUsed'))
            except Exception:
                # parabluDiskBytes = 0
                parabluDiskUsage = "N/A"
            
            moreDetails.update({'/parablu Usage':[parabluDiskUsage]})

            try:
                parabluDisk = cursorFinal.get('parabluDiskAvailable')+"B"
                my_logger.info("The below is the parablu disk space")
                my_logger.info(parabluDisk)
                if parabluDisk == "0B":
                    parabluDisk = "N/A"

            
            except Exception:
    
                parabluDisk = "N/A"
            
            moreDetails.update({'/parablu Available':[parabluDisk]})


            my_logger.info("=================================Parablu Disk Details===========================================")
            try:
                
                Mongo.update({'Mongo Backup Folder Size':[cursorFinal.get('MongoBackupFolder')+"B"]})
            except Exception:
                Mongo.update({'Mongo Backup Folder Size':["0"+"B"]})
            
            try:
                nightlyRestart = cursorFinal.get('lastNightlyRestart')
                if nightlyRestart is not None or nightlyRestart != "N/A" or nightlyRestart != "0" or nightlyRestart != 0:
                    my_logger.info("The value of the nightly restart us ")
                    my_logger.info(nightlyRestart)
                    recordedDate = cursorFinal.get('Date & Time ')
                    recordedDate = datetime.strptime(recordedDate, "%Y/%m/%d %H:%M:%S")
                    recordedDate = recordedDate.strftime("%b %d %Y %H:%M")


                    date = nightlyRestart.replace('IST', '+0530')
                    date_obj = datetime.strptime(date, '%a %b %d %H:%M:%S %z %Y')
                    formatted_date2 = datetime.strftime(date_obj, '%b %d %Y %H:%M')

                    nightlyRestartColor = compareDateWithDays(recordedDate,formatted_date2,1)

                else:
                    nightlyRestartColor = "red"

                moreDetails.update({'Nightly Restart':[cursorFinal.get('lastNightlyRestart'),nightlyRestartColor]})

            except Exception:
                my_logger.info("I am in line 2651")
                my_logger.info("I am in the exception")
                nightlyRestartColor = "red"
                moreDetails.update({'Nightly Restart':["0",nightlyRestartColor]})
            

            my_logger.info("-=======================================================================================================--")

            try:
                uploadFolder = cursorFinal.get('UploadFolder')+"B"
                # my_logger.info("The value of the Upload Folder size is : "+ uploadFolder)
                uploadFolderBytes = convert_to_bytes(cursorFinal.get('UploadFolder'))
                
            except Exception:
                uploadFolderBytes = 0
                uploadFolder = "0"+"B"



            try:
                percentageuploadFolder= (int(uploadFolderBytes) * 100)/int(parabluDiskBytes)
                my_logger.info("The value of the poercentage tmp chunk is ")
                my_logger.info(percentageuploadFolder)
                my_logger.info("This is the try catch")
            except:
                my_logger.info("This is the except catch")
                percentageuploadFolder = 0
                my_logger.info("The value of the poercentage tmp chunk is ")
                my_logger.info(percentageuploadFolder)


            if(percentageuploadFolder < 35):
                uploadFolderColor = "darkgreen"
            else:
                uploadFolderColor = "red"
        
            my_logger.info("The System Name is  :1799")
            uploadFolderName = "/parablu"+"/"+resValue+"/upload"


            my_logger.info("The value of yhje upload Folder Color is ")
            my_logger.info(uploadFolderColor)
            my_logger.info("The value of ytje percentage of ythe upload folder size is ")
            my_logger.info(percentageuploadFolder)
        


            moreDetails.update({uploadFolderName:[uploadFolder,uploadFolderColor]})
            print(userid)

            try:
                Mongo.update({'Mongo DB Storage':[cursorFinal.get('MongoDb')+"B"]})
            except Exception:
                Mongo.update({'Mongo DB Storage':["0"]})

            
            try:
                tmpChunkFolder = cursorFinal.get('tmpFolder')+"B"
                tmpChunkFolderBytes = convert_to_bytes(cursorFinal.get('tmpFolder'))
                my_logger.info("the value of the tmpchunk folder in byters")
                my_logger.info(tmpChunkFolderBytes)
            except Exception:
                tmpChunkFolderBytes = 0
                tmpChunkFolder = "0"+"B"
            
            try:
                percentagetmpChunk = (int(tmpChunkFolderBytes) * 100)/int(parabluDiskBytes)
            except:
                percentagetmpChunk = 0
                


            if(percentagetmpChunk < 25):
                tmpChunkColor = "darkgreen"
            else:
                tmpChunkColor = "red"

            tmpChunkFolderSize = "/parablu/tmp-chunk"
            moreDetails.update({tmpChunkFolderSize:[tmpChunkFolder,tmpChunkColor]})

            my_logger.info("================================TMP CHUNK FOLDER COMPLETED============================================================================")
            my_logger.info("The System Name is  :1807")
            try:
                fFolderSize = cursorFinal.get('fFolderSize')
                fFolderSizeBytes = convert_to_bytes(cursorFinal.get('fFolderSize'))
            except Exception as e:
                my_logger.info(e)
                fFolderSizeBytes = 100000000000000000
                fFolderSize = "N/A"

            fFolderSizename = "/parablu"+"/"+resValue+"/f"

            if(fFolderSizeBytes <= 8192):
                fFolderSizeColor = "darkgreen"
            else:
                fFolderSizeColor = "red"
            
            my_logger.info("The value of the ffoldersize in bytes color is : "+ fFolderSizeColor)
            my_logger.info("The value of the ffoldersize in bytes color is : "+ fFolderSizename)

            moreDetails.update({fFolderSizename:[fFolderSize,fFolderSizeColor,resValue]})
            my_logger.info("The System Name is  :1816")


            my_logger.info("===============================COMPLETED F FOLDER SIZE=================================================================")

            try:
                physical.update({'RAM':[cursorFinal.get('Total Physical Memory')]})
                totalRam = cursorFinal.get('Total Physical Memory')
                my_logger.info("the total ram of the system is ")
                my_logger.info(totalRam)

            except Exception:
                physical.update({'RAM':["0"]})
            
            try:
                usedPhyMem = cursorFinal.get('Used Physical Memory')
                my_logger.info("The used Physical memory is ")
                my_logger.info(usedPhyMem)
                if((totalRam != "-" or totalRam is not None or totalRam != "N/A") and (usedPhyMem != "-" or usedPhyMem is not None or usedPhyMem != "N/A")):
                    # result = compareDate(lastMongoBackup,1)
                    my_logger.info("The value of the total physical memory is : " + totalRam)
                    my_logger.info("The value of the used physical memory is : " + usedPhyMem)

                    try:
                        finalPercentage = (int(usedPhyMem) * 100)/int(totalRam)
                    except Exception:
                        finalPercentage = 0


                    my_logger.info("The percentager of the used memory is : ")
                    my_logger.info(finalPercentage)
                    if finalPercentage > 90:
                        phyStatus = "red"
                    else:
                        phyStatus = "green"
                
                else:
                    physicalMemory = "N/A"
                    phyStatus = "red"

                physical.update({'Used RAM':[cursorFinal.get('Used Physical Memory'),phyStatus]})
            except Exception:
                physical.update({'Used RAM':["0","red"]})
            

            try:
                physical.update({'Free RAM':[cursorFinal.get('Free Physical Memory')]})
            except Exception:
                physical.update({'Free RAM':["0"]})
            
            # try:
            #     physical.update({'Shared Memory':[cursorFinal.get('Shared Memory')]})
            # except Exception:
            #     physical.update({'Shared Memory':["0"]})
            

            try:
                physical.update({'Buff and Cache ':[cursorFinal.get('Buff/Cache')]})
            except Exception:
                physical.update({'Buff and Cache ':["0"]})
            

            try:
                availableMemory = cursorFinal.get('Available')
                availablePercentage = (100 * int(availableMemory))/int(totalRam)
                finalAvailablePercentagehere = 100 - availablePercentage
                physical.update({'Available for Application':[cursorFinal.get('Available'),finalAvailablePercentagehere]})

            except Exception:
                physical.update({'Available for Application':["N/A"]})
            

            try:
                totalSpace = convert_to_bytes2(cursorFinal.get('Total Space'))
                my_logger.info('The total Space is at line 3423 is ')
                my_logger.info(totalSpace)
                physical.update({'Disk Space':[cursorFinal.get('Total Space')]})
            except Exception:
                totalSpace = 0
                physical.update({'Disk Space':["N/A"]})
            
            my_logger.info("The System Name is  :1823")
            try:
                freeSpace = convert_to_bytes2(cursorFinal.get('Free Space'))
                my_logger.info('The total Space is at line 3433 is ')
                my_logger.info(freeSpace)
                physical.update({'Disk Free':[cursorFinal.get('Free Space')]})
            except Exception:
                freeSpace = 0
                physical.update({'Disk Free':["N/A"]})



            try:
                UsedSpace = convert_to_bytes2(cursorFinal.get('Usable Space'))
                UsedSpacePercentage = (int(UsedSpace) * 100) / int(totalSpace)
                physical.update({'Disk Used':[cursorFinal.get('Usable Space') ,UsedSpacePercentage]})
            except Exception as e:
                my_logger.error(e)
                physical.update({'Disk Used':["N/A" ,0]})
            
            # UsedSpace = int(totalSpace) - int(freeSpace)
            # my_logger.info("Yje valiue of the used Space is ")
            # my_logger.info(UsedSpace)
            # my_logger.info("Line number 3443")
            # UsedSpacePercentage = (100 * UsedSpace) / int(totalSpace)
            # UsedSpacePercentage = UsedSpacePercentage

            # UsedSpace = UsedSpace / 1024
            # UsedSpace = UsedSpace / 1024
            # UsedSpace = UsedSpace / 1024

            # physical.update({'Disk Used':[str(round(UsedSpace,2)) +" GB" ,UsedSpacePercentage]})

            my_logger.info("The System Name is  :1826")

            try:
                swapSpace = cursorFinal.get('Swap Memory / Disabled')
                my_logger.info("The value of the swap space is : ")
                my_logger.info(swapSpace)
                if(int(swapSpace) > int(totalRam) * 2):
                    swapColor = "green"
                else:
                    swapColor = "red"
                physical.update({'Swap Space':[cursorFinal.get('Swap Memory / Disabled'),swapColor]})
            except Exception:
                swapSpace = 0
                physical.update({'Swap Space':["N/A"]})
            
            my_logger.info("The System Name is  :1827")
            
            try:
                rateLimiter = cursorFinal.get('rateLimiter')
                if rateLimiter is not None:
                    physical.update({'Mongo Rate Limit':[int(float(rateLimiter))]})
                else:
                    physical.update({'Mongo Rate Limit':["N/A"]})
            except Exception:
                physical.update({'Mongo Rate Limit':["N/A"]})


            try:
                threadPool = cursorFinal.get('poolThread')
                if threadPool is not None:
                    physical.update({'Pool Thread Count':[int(float(threadPool))]})
                else:
                    physical.update({'Pool Thread Count':["N/A"]})
            except Exception:
                physical.update({'Pool Thread Count':["N/A"]})





            try:
                Mongo.update({'Mongo Cap Size':[cursorFinal.get('MongoCapValue')]})
            except Exception:
                Mongo.update({'Mongo Cap Size':["0"]})
            
            my_logger.info("The System Name is  :1830")

            try:
                patchfileSize = cursorFinal.get('patchFileSize')+"B"
                patchfileSizeBytes = convert_to_bytes(cursorFinal.get('patchFileSize'))
                my_logger.info("The Paych file iuze oid : ")
                my_logger.info(patchfileSizeBytes)
            except Exception:
                my_logger.info("This is the exception : ")
                patchfileSize = "0"
                patchfileSizeBytes = 0

            
            
            if(patchfileSizeBytes <= 40000000000):
                patchfileSizeColor = "darkgreen"
            else:
                patchfileSizeColor = "red"

            my_logger.info("The System Name is  :1832")
            patchFolderSize = "/installables/patch"

            moreDetails.update({patchFolderSize:[patchfileSize,patchfileSizeColor]})



            my_logger.info("==========================================PATCH FILE SIZE==============================================================")
            
            syncFolderName = "/parablu"+"/"+resValue+"/sync-upload"
            try:
                syncFolder = cursorFinal.get('SyncFolderSize') +"B"
                syncFolderBytes = convert_to_bytes(cursorFinal.get('SyncFolderSize'))
                my_logger.info("The Sync folder Bytes is : ")
                my_logger.info(syncFolderBytes)

            except Exception:
                syncFolder = "0"
                syncFolderBytes = 0
            
            if(syncFolderBytes <= 8192):
                syncFolderBytesColor = "darkgreen"
            else:
                syncFolderBytesColor = "red"

            moreDetails.update({syncFolderName:[syncFolder,syncFolderBytesColor]})
            my_logger.info("The System Name is  :1833")
            print("The Sync Folder Size is : " + syncFolder)
            
            try:
                backupPolicy = cursorFinal.get('BackupPolicy')
            except Exception:
                backupPolicy = "N/A"


            my_logger.info("==================================================LINE 3821=====================================================")
            my_logger.info(backupPolicy)
            my_logger.info("=================================================LINE 3823=======================================================")

            if(backupPolicy == "enabled"):
                backupPolicyColor = "darkgreen"
            else:
                backupPolicyColor = "red"

            # moreDetails.update({"Dedup Backup Policy":[backupPolicy,backupPolicyColor]})
            
            try:
                if(int(str(cursorFinal.get('outgoingUtilized'))) < 0 ):
                    print(int(str(cursorFinal.get('OutgoingThread'))))
                    Tomcat.update({'Outgoing Utilized':["-1"]})
                else:
                    Tomcat.update({'Outgoing Utilized':[cursorFinal.get('outgoingUtilized')]})
            except Exception:
                Tomcat.update({'Outgoing Utilized':["0"]})

            try:
                uploadFileSizeLimit = cursorFinal.get('uploadFileSizeLimitInMB')
                my_logger.info("The upload file size limit is ")
                my_logger.info(uploadFileSizeLimit)
                if(int(uploadFileSizeLimit) == 1):
                    uploadFileSizeLimitColor = "darkgreen"
                else:
                    uploadFileSizeLimitColor = "red"
                Tomcat.update({'Upload File Size Limit':[cursorFinal.get('uploadFileSizeLimitInMB') + "MB",uploadFileSizeLimitColor]})
            except Exception:
                Tomcat.update({'Upload File Size Limit':["N/A"]})
            
            try:
                Tomcat.update({'Memory Partition Tomcat JOB1':[cursorFinal.get('MemoryPartTomjob') + "MB"]})
            except Exception:
                Tomcat.update({'Memory Partition Tomcat JOB1':["0"]})
            
            try:
                Tomcat.update({'Memory Partition Tomcat PCB1':[cursorFinal.get('MemoryPartTompcb') + "MB"]})
            except Exception:
                Tomcat.update({'Memory Partition Tomcat PCB1':["0"]})
            


            try:
                news.update({'Blukrypt Status':[cursorFinal.get('BlukryptStatus')]})
            except Exception:
                news.update({'Blukrypt Status':["0"]})
            
            # news.update({'Mongo Last Backup was Done on':[j['MongoLastBackup']]})
            try:
                news.update({'Number of 429 in outgoing':[cursorFinal.get('Grep429')]})
            except Exception:
                news.update({'Number of 429 in outgoing':["0"]})
            
            my_logger.info("The System Name is  :1868")


            

    return jsonify({'htmlresponse': render_template('dashboard/testResponse.html',res = resValue,employeelist=System,apach = Apache,mong = Mongo,tom = Tomcat,moreDet = moreDetails,physical=physical)})



@admin.route("/BlockUsers",methods=['GET','POST'])
def blockUsers():
    if request.method == 'POST':
        cloudName = request.form['userid']

        # print("The user Id I am recieving"+userid)
        
        # print("The clud name is : "+ cloudNe)

        # print("The above blockedUsers")
        blockedUsers = blkuser.find_one({'cloudName': cloudName},sort=[("_id",pymongo.DESCENDING)])

        print(blockedUsers.get('BlockUsers'))
        blockListUsersList = blockedUsers.get('BlockUsers')
        blockListUsersList = list(filter(None, blockListUsersList))

    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = blockListUsersList)})


@is_logged_in
@admin.route("/LicenceMore",methods=['GET','POST'])
def LicenceMore():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))

    if request.method == 'POST':
        userid = request.form['userid']
      
        licenceAdillllll = LicenceDataAddil.find_one({"cloudName":userid},sort=[("_id",pymongo.DESCENDING)])

        # for i in licenceAdillllll:
        LicenceArray = licenceAdillllll.get('LicenceAdditional')

    return jsonify({'htmlresponse': render_template('dashboard/LicenceEnabled.html',LicenceDetails = LicenceArray)})



@is_logged_in
@admin.route("/clickMore",methods=['GET','POST'])
def clickMore():
    if not session.get('logged_in'):
        return redirect(url_for('authentication_blueprint.login'))

    if session.get('logged_in'):
        user = auth.find_one({"username": session['username']})
        usersSession = sessions_collection.find_one({"user_id":user['_id']})
        
        if usersSession is not None:
            checkOld = usersSession["session_id"]
            if checkOld != session["session_id"]:
                session.pop('username', None)
                session.clear()
                flash('You logged in at different device', 'warning')
                return redirect(url_for("authentication_blueprint.login"))

        else:
            session.pop('username', None)
            session.clear()
            flash('Make a new login!!!', 'warning')
            return redirect(url_for("authentication_blueprint.login"))
        
    news = {}
    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        res = userid.partition(".parablu.com")[0]
        addCloudPrefix = "cloud_"+res
        mycollection=dbs[addCloudPrefix]
        cursor = mycollection.find({"System Name":userid})
        

        for i in cursor:
            print(i)
            news.update({'System Name':[i['System Name']]})
            news.update({'Parablu Disk Mounted':[i['parabluDiskMounted']]})
            news.update({'/parablu':[i['parabluDiskAvailable']]})
            news.update({'Mongo Backup Folder Size':[i['MongoBackupFolder']]})
            news.update({'Upload Folder Size':[i['UploadFolder']]})
            news.update({'Mongo DB Storage':[i['MongoDb']]})
            news.update({'Tmp-chunck folder size':[i['tmpFolder']]})


    return jsonify({'htmlresponse': render_template('dashboard/moreinfo.html',employeelist=news)})


@is_logged_in
@admin.route("/apacheDetails",methods=['GET','POST'])
def apacheDetails():
    news = {}
    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        res = userid.partition(".parablu.com")[0]
        addCloudPrefix = "cloud_"+res
        mycollection=dbs[addCloudPrefix]
        cursor = mycollection.find({"System Name":userid})
        rams = {}

        for i in cursor:
            news.update({'Start Server':[i['StartServer']]})
            news.update({'minimum Spare Server':[i['minSpareServer']]})
            news.update({'maximum Spare Server':[i['maxSpareServer']]})
            news.update({'Maximum Request Workers':[i['MaxRequestWorkers']]})
            news.update({'Maximum Connections Per Child':[i['MaxConnectionsPerChild']]})
            news.update({'Maximum Clients':[i['MaxClients']]})
            news.update({'Server Limit':[i['ServerLimit']]})
            
            rams.update({'Total Physical Memory':[i['Total_Physical_Memory']]})
            rams.update({'Used Physical Memory':[i['Used_Phy_Mem']]})
            rams.update({'Free Physical Memory':[i['Free_Phy_Mem']]})
            rams.update({'Swap Space':[i['Swap_Mem']]})
            rams.update({'Shared Memory':[i['Shared Memory']]})
            rams.update({'Buffer and Cache Memory':[i['Buff / Cache']]})
            rams.update({'Available':[i['Available']]})


    return jsonify({'htmlresponse': render_template('dashboard/apacheDetails.html',employeelist=news,employee = rams)})

import pandas as pd
import os

@admin.route("/download202/<string:res>")
def download202(res): 
    print("Hello this is the value")
    print(res)
    my_logger.info("The value of the res is:"+ res)

    path = "/home/ubuntu/OpcenterFiles/"+res+"/statistic.xlsx"
    #pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/back202.xlsx"
    #df = pd.read_excel(path, sheet_name='blacktwo')
    #df.to_excel(pathUpdate, index=False)
    #print("Downloading")
    #return send_file(pathUpdate, as_attachment=True)
    if os.path.isfile(path):
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/back202.xlsx"
        df = pd.read_excel(path, sheet_name='blacktwo')
        df.to_excel(pathUpdate, index=False)
        print("Downloading")
        return send_file(pathUpdate, as_attachment=True)
    else:
        clientName = findHostNameWithSystem(res)
        newPath = "/home/ubuntu/OpcenterFiles/"+clientName+"/statistic.xlsx"
        df = pd.read_excel(newPath, sheet_name='blacktwo')
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+clientName+"/back202.xlsx"
        df.to_excel(pathUpdate, index=False)
        return send_file(pathUpdate, as_attachment=True)
    

#@admin.route("/download202/<string:res>")
#def cloudBuckts(res):
#    print("Hello this is the value")
 #   print(res)
  #  path = "/home/ubuntu/OpcenterFiles/"+res+"/statistic.xlsx"
   # pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/back202.xlsx"
   # df = pd.read_excel(path, sheet_name='blacktwo')
   # df.to_excel(pathUpdate, index=False)
   # print("Downloading")
#    return send_file(pathUpdate, as_attachment=True)



@admin.route("/addOwners",methods=['POST'])
def addOwners():
    print("Helloworld")
    names = CloudName.distinct("CloudName")
    print(names)
    spoc = db.UsersData
    spocs = spoc.distinct("username")
    print("-----------------------------------------------------------------------------------------------------------------")
    return render_template("dashboard/addOwners.html",cloudNames = names,spo = spocs)


@admin.route("/saveSpoc",methods=['GET','POST'])
def addSpoc():
    if request.method == 'POST':
        machines = request.form.get('dropdown1')
        spocNames = request.form.get('dropdown2')
        machineType = request.form.get('dropdown3')
        print("The Machine Type is : "+ machineType)

        document = auth.find_one({"username": spocNames })
        if document:
            email = document["email"]
            spocId = document["_id"]
            print("the below is the id : ")
            print(spocId)


        filter = {"CloudName":machines}
        update = {"$set": {"Owner": spocId, "MachineType": machineType}}

        CloudName.update_many(filter, update)
        return redirect(url_for('admin.dashboard'))
    return "ERROR ERROR ERROR"


@admin.route("/testMacha")
def testMacha():
    
    return render_template("accounts/timeglass.html")


@admin.route("/dedupDisabled",methods=['GET','POST'])
def dedupDisabled():
    my_logger.info("--------------------------------------------------------------=====================================================================")
    my_logger.info("This is line number 4404")
    if request.method == 'POST':
        userid = request.form['userid']
        print("The value of userId is : "+ userid)


        backupPolicyDataCollection = dbs["backupPolicyList"]

        backupPolicyData = backupPolicyDataCollection.find_one({"cloudName":userid}, sort=[('_id', pymongo.DESCENDING)])
        backupPolicies = []
        if backupPolicyData is not None:
            my_logger.info("I am in line 1697")
            backupPolicies = backupPolicyData.get("backupPolicyList")
            my_logger.info(backupPolicies)
            my_logger.info("The above is the backuppolicies from he line 1696")
            my_logger.info("The Backup Policy having disabled is")
            my_logger.info(len(backupPolicies))
            totalNumber = str(len(backupPolicies)) + " Policies"
            
        else:
            my_logger.info("I am in line 1703")

    return jsonify({'htmlresponse': render_template('dashboard/backupPolicy.html',backupPolicies = backupPolicies)})



@admin.route("/oneDriveBucketDown/<string:res>")
def oneDriveBucketDown(res):
    print("Hello this is the value")
    print(res)

    path = "/home/ubuntu/OpcenterFiles/"+res+"/statistic.xlsx"
    if os.path.isfile(path):
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/storage.xlsx"
        df = pd.read_excel(path, sheet_name='StorageExceeded')
        df.to_excel(pathUpdate, index=False)
        print("Downloading")
        return send_file(pathUpdate, as_attachment=True)
    else:
        clientName = findHostNameWithSystem(res)
        newPath = "/home/ubuntu/OpcenterFiles/"+clientName+"/statistic.xlsx"
        df = pd.read_excel(newPath, sheet_name='StorageExceeded')
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+clientName+"/storage.xlsx"
        df.to_excel(pathUpdate, index=False)
        return send_file(pathUpdate, as_attachment=True)



@admin.route("/download404/<string:res>")
def download404(res):
    print("Hello this is the value")
    print(res)
    path = "/home/ubuntu/OpcenterFiles/"+res+"/statistic.xlsx"
    if os.path.isfile(path):
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/back404.xlsx"
        df = pd.read_excel(path, sheet_name='blackfour')
        df.to_excel(pathUpdate, index=False)
        print("Downloading")
        return send_file(pathUpdate, as_attachment=True)
    else:
        clientName = findHostNameWithSystem(res)
        newPath = "/home/ubuntu/OpcenterFiles/"+clientName+"/statistic.xlsx"
        df = pd.read_excel(newPath, sheet_name='blackfour')
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+clientName+"/back404.xlsx"
        df.to_excel(pathUpdate, index=False)
        return send_file(pathUpdate, as_attachment=True)


@admin.route("/cloudBucketDown/<string:res>")
def cloudBucketDownload(res):
    print("Hello this is the value")
    print(res)

    path = "/home/ubuntu/OpcenterFiles/"+res+"/muxFile.xlsx"
    if os.path.isfile(path):
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/muxFileNew.xlsx"
        df = pd.read_excel(path, sheet_name='usersMux')
        df.to_excel(pathUpdate, index=False)
        print("Downloading")
        return send_file(pathUpdate, as_attachment=True)
    else:
        clientName = findHostNameWithSystem(res)
        newPath = "/home/ubuntu/OpcenterFiles/"+clientName+"/muxFile.xlsx"
        df = pd.read_excel(newPath, sheet_name='usersMux')
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+clientName+"/muxFileNew.xlsx"
        df.to_excel(pathUpdate, index=False)
        return send_file(pathUpdate, as_attachment=True)



@admin.route("/muxUsers/<string:res>")
def macUsers(res):
    print("Hello this is the value")
    print(res)
    path = "/home/ubuntu/OpcenterFiles/"+res+"/muxFile.xlsx"
    if os.path.isfile(path):
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/muxFileNew.xlsx"
        df = pd.read_excel(path, sheet_name='usersMux')
        df.to_excel(pathUpdate, index=False)
        print("Downloading")
        return send_file(pathUpdate, as_attachment=True)
    else:
        clientName = findHostNameWithSystem(res)
        newPath = "/home/ubuntu/OpcenterFiles/"+clientName+"/muxFile.xlsx"
        df = pd.read_excel(newPath, sheet_name='usersMux')
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+clientName+"/muxFileNew.xlsx"
        df.to_excel(pathUpdate, index=False)
        return send_file(pathUpdate, as_attachment=True)




@admin.route("/bucketsList/<string:res>")
def bucketList(res):
    print("Hello this is the value")
    print(res)
    path = "/home/ubuntu/OpcenterFiles/"+res+"/muxFile.xlsx"
    if os.path.isfile(path):
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+res+"/bucketList.xlsx"
        df = pd.read_excel(path, sheet_name='MuxDetails')
        df.to_excel(pathUpdate, index=False)
        print("Downloading")
        return send_file(pathUpdate, as_attachment=True)
    else:
        clientName = findHostNameWithSystem(res)
        newPath = "/home/ubuntu/OpcenterFiles/"+clientName+"/muxFile.xlsx"
        df = pd.read_excel(newPath, sheet_name='MuxDetails')
        pathUpdate = "/home/ubuntu/OpcenterFiles/"+clientName+"/bucketList.xlsx"
        df.to_excel(pathUpdate, index=False)
        return send_file(pathUpdate, as_attachment=True)



@admin.route("/serverHistory",methods=['GET','POST'])
def historySystem():
    my_logger.info("This is the history system")
    my_logger.info("I am coming to this route")
    if request.method == 'POST':
        systemName = request.form['userid']
        cloudName = request.form['res']

        my_logger.info("The System Name is : "+ systemName)
        my_logger.info("The cloud name is : "+cloudName)

        addCloudPrefix = "cloud_"+cloudName
        print("the value of the add cloudprefix is : "+addCloudPrefix )
        mycollection=dbs[addCloudPrefix]

        print("The suystem name is : "+systemName)
        cursorFinal = mycollection.find({'System Name':systemName}).sort("Date & Time ",-1).limit(10)
        print("the cursor final is the : ")
        print(cursorFinal)
        print("The below is the limit 10 documents")
        oldData = []
        for i in cursorFinal:
            print(i)
            oldData.append(i)

        print("The total documents are : ")
        print(len(oldData))
        my_logger.info("The value of the document from the database is ")
        my_logger.info(cursorFinal)

        
    return jsonify({'htmlresponse': render_template('dashboard/systemHistory.html',datas = oldData,res = cloudName)})


@admin.route("/serverUptimeHistory",methods=['GET','POST'])
def serverUptimeHistory():
    print("Hello World")
    print("Line number 2547")
    System = {}
    Apache = {}
    Mongo = {}
    Tomcat = {}
    news = {}
    rams = {}
    physical = {}
    moreDetails = {}
    if request.method == "POST":
        systemName = request.form['userid']
        date = request.form['res']
        print("The value of the date is : ")
        print(date)
        cloudName = request.form['cloudName']

        print("The Cloud Name : " + cloudName)

        addCloudPrefix = "cloud_"+cloudName
        mycollection=dbs[addCloudPrefix]

        cursorFinal = mycollection.find_one({'System Name': systemName, 'Date & Time ': date})

        print("The value of the cursor is below")
        print(cursorFinal)
        my_logger.info("The System Name is  :")
        
        # for j in cursorFinal:
        # insideListCursor.append(cursorFinal.get('cronUptime'))
        try:
            Mongo.update({'Mongo Version':[cursorFinal.get('Mongo Version')]})
        except Exception:
            Mongo.update({'Mongo Version':["0"]})

        try:
            Mongo.update({'MongoLastBackup':[cursorFinal.get('lastMongoUpdate')]})
        except Exception:
            Mongo.update({'MongoLastBackup':["0"]})

        try:
            Mongo.update({'MongoLastBackup':[cursorFinal.get('lastMongoUpdate')]})
        except Exception:
            Mongo.update({'MongoLastBackup':["0"]})

        try:
            System.update({'System Name':[cursorFinal.get('System Name')]})
        except Exception:
            System.update({'System Name':["0"]})

        try:
            Apache.update({'Apache2 Uptime':[cursorFinal.get('Apache2Uptime')]})
        except Exception:
            Apache.update({'Apache2 Uptime':["0"]})
        

        try:
            Tomcat.update({'Tomcat PCB 1 Uptime':[cursorFinal.get('tomcatpcb1Uptime')]})
        except Exception:
            Tomcat.update({'Tomcat PCB 1 Uptime':["0"]})

        try:
            Tomcat.update({'Tomcat JOB 1 Uptime':[cursorFinal.get('tomcatjob11Uptime')]})
        except Exception:
            Tomcat.update({'Tomcat JOB 1 Uptime':["0"]})

        
        try:
            news.update({'Memcached Uptime':[cursorFinal.get('memcachedUptime')]})
        except Exception:
            news.update({'Memcached Uptime':["0"]})
        
        try:
            System.update({'Cron Uptime':[cursorFinal.get('cronUptime')]})
        except Exception:
            System.update({'Cron Uptime':["0"]})
        
        try:
            Mongo.update({'Mongo Uptime':[cursorFinal.get('mongodUptime')]})
        except Exception:
            Mongo.update({'Mongo Uptime':["0"]})
        
        
        try:
            System.update({'System Uptime':[cursorFinal.get('SystemUptime')]})
        except Exception:
            System.update({'System Uptime':["0"]})

        
        
        my_logger.info("The System Name is  :1779")
        
        try:
            Tomcat.update({'Incoming Thread Set':[cursorFinal.get('IncomingThread')]})
        except Exception:
            Tomcat.update({'Incoming Thread Set':["0"]})
        
        try:
            Tomcat.update({'Incoming Utilized':[cursorFinal.get('IncomingUtilized')]})
        except Exception:
            Tomcat.update({'Incoming Utilized':["0"]})
        

        try:
            Tomcat.update({'Outgoing Thread Set':[cursorFinal.get('OutgoingThread')]})
        except Exception:
            Tomcat.update({'Outgoing Thread Set':["0"]})
        
        my_logger.info("The System Name is  :1784")
        try:
            Apache.update({'Minimum Spare Server':[cursorFinal.get('minSpareServer')]})
        except Exception:
            Apache.update({'Minimum Spare Server':["0"]})
        
        try:
            Apache.update({'Maximum Spare Server':[cursorFinal.get('maxSpareServer')]})
        except Exception:
            Apache.update({'Maximum Spare Server':["0"]})
        
        try:
            Apache.update({'Maximum Request Workers':[cursorFinal.get('MaxRequestWorkers')]})
        except Exception:
            Apache.update({'Maximum Request Workers':["0"]})
        

        try:
            Apache.update({'Maximum Connections Per Child':[cursorFinal.get('MaxConnectionsPerChild')]})
        except Exception:
            Apache.update({'Maximum Connections Per Child':["0"]})
        
        try:
            Apache.update({'Maximum Clients':[cursorFinal.get('MaxClients')]})
        except Exception:
            Apache.update({'Maximum Clients':["0"]})
        

        try:
            Apache.update({'Server Limit':[cursorFinal.get('ServerLimit')]})
        except Exception:
            Apache.update({'Server Limit':["0"]})
        
        my_logger.info("The System Name is  :1791")
        try:
            moreDetails.update({'System Name':[cursorFinal.get('System Name')]})
        except Exception:
            moreDetails.update({'System Name':["0"]})
        

        try:
            moreDetails.update({'Parablu Disk Mounted':[cursorFinal.get('parabluDiskMounted')]})
        except Exception:
            moreDetails.update({'Parablu Disk Mounted':["0"]})
        
        try:
            parabluDisk = cursorFinal.get('parabluDiskAvailable')+"B"
        except Exception:
            parabluDisk = "0B"
        
        moreDetails.update({'/parablu':[parabluDisk]})
        try:
            Mongo.update({'Mongo Backup Folder Size':[cursorFinal.get('MongoBackupFolder')+"B"]})
        except Exception:
            Mongo.update({'Mongo Backup Folder Size':["0"+"B"]})
        
        try:
            moreDetails.update({'Nightly Restart':[cursorFinal.get('lastNightlyRestart')]})
        except Exception:
            moreDetails.update({'Nightly Restart':["0"]})
        

        try:
            uploadFolder = cursorFinal.get('UploadFolder')+"B"
        except Exception:
            uploadFolder = "0"+"B"
        
        my_logger.info("The System Name is  :1799")
        uploadFolderName = "/parablu"+"/"+cloudName+"/upload"
        moreDetails.update({uploadFolderName:[uploadFolder]})


        try:
            Mongo.update({'Mongo DB Storage':[cursorFinal.get('MongoDb')+"B"]})
        except Exception:
            Mongo.update({'Mongo DB Storage':["0"]})

        my_logger.info("The System Name is  :2732")
        try:
            tmpChunkFolder = cursorFinal.get('tmpFolder')+"B"
        except Exception:
            tmpChunkFolder = "0"+"B"
        
        tmpChunkFolderSize = "/parablu/tmp-chunk"
        moreDetails.update({tmpChunkFolderSize:[tmpChunkFolder]})
        my_logger.info("The System Name is  :1807")
        try:
            fFolderSize = cursorFinal.get('fFolderSize')
            my_logger.info("The System Name is  :1810")
        except KeyError:
            fFolderSize = "N/A"

        fFolderSizename = "/parablu"+"/"+cloudName+"/f"
        
        moreDetails.update({fFolderSizename:[fFolderSize]})
        my_logger.info("The System Name is  :1816")

        try:
            physical.update({'Total Memory':[cursorFinal.get('Total Physical Memory')]})
        except Exception:
            physical.update({'Total Memory':["0"]})
        
        try:
            physical.update({'Used Memory':[cursorFinal.get('Used Physical Memory')]})
        except Exception:
            physical.update({'Used Memory':["0"]})
        

        try:
            physical.update({'Free Memory':[cursorFinal.get('Free Physical Memory')]})
        except Exception:
            physical.update({'Free Memory':["0"]})
        
        try:
            physical.update({'Shared Memory':[cursorFinal.get('Shared Memory')]})
        except Exception:
            physical.update({'Shared Memory':["0"]})
        

        try:
            physical.update({'Buff and Cache Memory':[cursorFinal.get('Buff/Cache')]})
        except Exception:
            physical.update({'Buff and Cache Memory':["0"]})
        

        try:
            physical.update({'Available Memory':[cursorFinal.get('Available')]})
        except Exception:
            physical.update({'Available Memory':["N/A"]})
        

        try:
            physical.update({'System Space':[cursorFinal.get('Total Space')]})
        except Exception:
            physical.update({'System Space':["N/A"]})
        
        my_logger.info("The System Name is  :1823")
        try:
            physical.update({'Free Space':[cursorFinal.get('Free Space')]})
        except Exception:
            physical.update({'Free Space':["N/A"]})
        
        my_logger.info("The System Name is  :1826")

        try:
            physical.update({'Swap Space':[cursorFinal.get('Swap Memory / Disabled')]})
        except Exception:
            physical.update({'Swap Space':["N/A"]})
        
        my_logger.info("The System Name is  :1827")
        
        try:
            Mongo.update({'Mongo Cap Size':[cursorFinal.get('MongoCapValue')]})
        except Exception:
            Mongo.update({'Mongo Cap Size':["0"]})
        
        my_logger.info("The System Name is  :1830")
        try:
            patchfileSize = cursorFinal.get('patchFileSize')+"B"
        except Exception:
            patchfileSize = "0"
        
        my_logger.info("The System Name is  :1832")
        patchFolderSize = "/installables/patch"
        moreDetails.update({patchFolderSize:[patchfileSize]})
        syncFolderName = "/parablu"+"/"+cloudName+"/sync-upload"
        try:
            syncFolder = cursorFinal.get('SyncFolderSize') +"B"
        except Exception:
            syncFolder = "0"
        
        moreDetails.update({syncFolderName:[syncFolder]})
        my_logger.info("The System Name is  :1833")
        print("The Sync Folder Size is : " + syncFolder)
        
        try:
            backupPolicy = cursorFinal.get('BackupPolicy')
            my_logger.info("The value of Backup Policy : "+ backupPolicy)

        except Exception:
            backupPolicy = "N/A"
            my_logger.info("The exception goes into the exceptiom")
            
        

        # moreDetails.update({"Dedup Backup Policy":[backupPolicy]})
        
        try:
            if(int(str(cursorFinal.get('outgoingUtilized'))) < 0 ):
                print(int(str(cursorFinal.get('OutgoingThread'))))
                Tomcat.update({'Outgoing Utilized':["-1"]})
            else:
                Tomcat.update({'Outgoing Utilized':[cursorFinal.get('outgoingUtilized')]})
        except Exception:
            Tomcat.update({'Outgoing Utilized':["0"]})

        try:
            Tomcat.update({'Upload File Size Limit':[cursorFinal.get('uploadFileSizeLimitInMB') + "MB"]})
        except Exception:
            Tomcat.update({'Upload File Size Limit':["N/A"]})
        
        try:
            Tomcat.update({'Memory Partition Tomcat JOB1':[cursorFinal.get('MemoryPartTomjob') + "MB"]})
        except Exception:
            Tomcat.update({'Memory Partition Tomcat JOB1':["0"]})
        
        try:
            Tomcat.update({'Memory Partition Tomcat PCB1':[cursorFinal.get('MemoryPartTompcb') + "MB"]})
        except Exception:
            Tomcat.update({'Memory Partition Tomcat PCB1':["0"]})
        


        try:
            news.update({'Blukrypt Status':[cursorFinal.get('BlukryptStatus')]})
        except Exception:
            news.update({'Blukrypt Status':["0"]})
        
        # news.update({'Mongo Last Backup was Done on':[j['MongoLastBackup']]})
        try:
            news.update({'Number of 429 in outgoing':[cursorFinal.get('Grep429')]})
        except Exception:
            news.update({'Number of 429 in outgoing':["0"]})
        
        my_logger.info("The System Name is  :1868")


    return jsonify({'htmlresponse': render_template('dashboard/testResponse.html',res = cloudName,employeelist=System,apach = Apache,mong = Mongo,tom = Tomcat,moreDet = moreDetails,physical=physical)})

@admin.route("/oneDriveMisMatch",methods=['GET','POST'])
def oneDriveMisMatch():
    if request.method == 'POST':
        userid = request.form['userid']
        my_logger.info("The value of userId is : "+ userid)

        oneDriveMixedUsers = dbs["documentOneDriveMis"]

        oneDriveMixed = oneDriveMixedUsers.find_one({"cloudName":userid}, sort=[('_id', pymongo.DESCENDING)])

        oneDriveMixedUsersList = []
        if oneDriveMixed is not None:
            my_logger.info("I am in line 1697")
            backupPolicies = oneDriveMixed.get("OneDriveMisList")
            my_logger.info(backupPolicies)
            my_logger.info("The above is the backuppolicies from he line 1696")
            my_logger.info("The Backup Policy having disabled is")
            my_logger.info(len(backupPolicies))
            totalNumber = str(len(backupPolicies)) + " Users"
            
        else:
            my_logger.info("I am in line 1703")


    return jsonify({'htmlresponse': render_template('dashboard/backupPolicy.html',backupPolicies = backupPolicies)})



def is_website_running(url):
    try:
        response = requests.get(url)
        return response.status_code == 200
    except requests.exceptions.RequestException as e:
        print(e)
        return False


@admin.route("/checkUptime")
def checkUptime():  
    
    result = is_website_running(website_url)

    urls = ["https://poornakashi.site","https://poorneakashi.site","https://poornsakashi.site","https://ibrelbk.parablu.com/BluKryptBuilder/healthcheck/","https://poornakashi.site","https://ceat.parablu.com","https://egbu.embassyindia.com","https://egbu.embassyindia.com/paracloud/healthcheck/","https://excelra.parablu.com/paracloud/healthcheck/"]
    return render_template('dashboard/Uptime.html', website_url=website_url,urls = urls)



@admin.route('/ping')
def ping():
    url = request.args.get('url')
    if url:
        time.sleep(5)
        if(is_website_running(url)):
            return f"Up"
        else:
            return f"Down"
    else:
        return "Invalid URL"



@admin.route('/graph')
def machineUptimeGraph():
    name = "ceat.parablu.com"
    latest_documents = uptimeRobot.find({"fqdn":name}).sort("_id", -1).limit(1000)
    datetime_values = [doc.get("lastUpdateddatatime") for doc in latest_documents]
    pipeline = [
    {"$match": {"fqdn": name}}, # Filter documents where "name" is "poorna"
    {"$sort": {"_id": -1}},         # Sort by _id in descending order (most recent documents first)
    {"$limit": 1000},                # Limit to the last 100 documents
    {
        "$project": {
            "_id": 0,        # Exclude the _id field from the result
            "status": {
                "$cond": {
                    "if": {"$eq": ["$status", "successfull"]},
                    "then": 1,
                    "else": 0
                }
            }
        }
    }
    ]
    result = list(uptimeRobot.aggregate(pipeline))
    statuses = [entry["status"] for entry in result]

    # combined_list = [
    #     {"datetime_value": datetime, "status": res["status"]}
    #     for datetime, res in zip(datetime_values, result)
    # ]

    # return render_template('dashboard/graphUptime.html', data=combined_list)

    # return result
    return render_template('dashboard/graphUptime.html',timestamps=[],status=[],
    )

@admin.route('/data')
def get_data():
    return jsonify(data)


@admin.route("/showMachineUptime")
def showMachineUptime():
    return "this is the machine uptime"



@admin.route("/notesTable/<string:cloudname>",methods = ["POST","GET"])
def notesTable(cloudname):

    my_logger.info("The CloudName is : ")
    my_logger.info(cloudname)

    pipeline = [
        {"$match": {"cloudName": cloudname}},
        {"$group": {"_id": "$unique_id", "count": {"$sum": 1}, "latestDoc": {"$max": "$$ROOT"}}}
    ]

    unique_docs_with_counts = list(opcenterNotes.aggregate(pipeline))
    print(unique_docs_with_counts)

    listNotes = []
    
    for group in unique_docs_with_counts:
        modified = False
        unique_id = group['_id']
        count = group['count']
        timestamp = group['latestDoc']["timestamp"]
        dt_object = datetime.fromtimestamp(timestamp)
        formatted_datetime = dt_object.strftime("%d-%b-%y %I:%M %p")
        group['latestDoc']["dateTime"] = formatted_datetime
        if count > 1:
            modified = True
        group['latestDoc']["modified"] = modified
        listNotes.append(group.get("latestDoc"))
        print(f"Unique ID: {unique_id}, Document Count: {count}")

    # listNotes.sort(key=lambda x: datetime.strptime(x['latestDoc']['dateTime'], "%d-%b-%y %I:%M %p"), reverse=True)
    print(listNotes)
    return render_template("dashboard/notesPage.html",opcenterData = listNotes,cloudname = cloudname)



@admin.route("/editNotes",methods = ["POST","GET"])
def editNotes():
    if request.method == 'POST':
        id = request.form['id']
        cloudname = request.form['cloudname']
        print(id)
        object_id = ObjectId(id)
        opcenterData = opcenterNotes.find_one({"_id":object_id})
        print(opcenterData)
        notesContent = opcenterData.get("content")
        notesUniqueId = opcenterData.get("unique_id")
        print(notesContent)
    return jsonify({'htmlresponse': render_template('dashboard/notesedit.html',notesContent = notesContent,object_id=object_id,cloudname =cloudname,notesUniqueId = notesUniqueId)})



@admin.route("/addNotes",methods = ["POST","GET"])
def addNotes():
    if request.method == 'POST':
        userid = request.form['userid']
        print("This is notesTable") 
        print(userid)       
    return jsonify({'htmlresponse': render_template('dashboard/stickyNotes.html',userid = userid)})


@admin.route("/addContent",methods=["POST"])
def addContent():
    if request.method == 'POST':
        content = request.form['content']
        cloudName = request.form['cloudName']
        current_date = datetime.now()
        timestamp = current_date.timestamp()
        author = session['username']
        unique_id = int(timestamp) + random.randint(0,1000)

        collection = {
            "unique_id":unique_id,
            "content" : content,
            "timestamp" : timestamp,
            "author" : author,
            "cloudName" : cloudName
        }
        result = opcenterNotes.insert_one(collection)
        # inserted_id = result.inserted_id
        # CloudName.update_one(
        #     {"CloudName": clouDNaMe},
        #     {"$addToSet": {"notesid": inserted_id}}
        # )
        print("Successfully inserted")

    return redirect(url_for('admin.notesTable',cloudname=cloudName))


@admin.route("/editContent",methods=["POST"])
def editContent():
    if request.method == 'POST':
        content = request.form['content']
        notesUniqueId = request.form['notesUniqueId']

        print("The above is the notes unique id mentioned")
        print(notesUniqueId)
        cloudname = request.form['cloudname']
        print(cloudname)
        print("=======================================THE ABOVE IS THE CLOUD NAME=================================")
        current_date = datetime.now()
        timestamp = current_date.timestamp()
        author = session['username']
        collection = {
            "unique_id":int(notesUniqueId),
            "content" : content,
            "timestamp" : timestamp,
            "author" : author,
            "cloudName" : cloudname
        }

        print("The route was here")
        result = opcenterNotes.insert_one(collection)
        print("Successfully inserted")
    return redirect(url_for('admin.notesTable',cloudname=cloudname))


@admin.route("/notesTest")
def notesTest():
    cloudDetails = CloudName.find_one({"CloudName":"ceat"}, sort=[('_id', pymongo.DESCENDING)])
    notesId = cloudDetails.get("notesid")
    listNotes = []
    if notesId is not None:
        for noteid in notesId:
            object_id = ObjectId(noteid)
            opcenterData = opcenterNotes.find_one({"_id":object_id})
            listNotes.append(opcenterData)

    # listNotes.reverse()
    return render_template("dashboard/notesPage.html",opcenterData = listNotes)



@admin.route("/writeNotes",methods=["POST"])
def writeNotes():
    if request.method == 'POST':
        cloudname = request.form['cloudname']
        print(cloudname)
        print("The above is the cloudname")
    return jsonify({'htmlresponse': render_template('dashboard/notesadd.html',cloudname = cloudname)})



@admin.route("/modified",methods=["POST"])
def modified():
    if request.method == 'POST':
        print("====================================================================================================")
        id = int(request.form['id'])
        cloudname = request.form['cloudname']
        newid = ObjectId(request.form['newid'])

        print("The original object id is")
        print(newid)        
        print("The value of the id is ")
        print(id)

        print("The value of the cloudName")
        print(cloudname)

        result = opcenterNotes.find({"cloudName": cloudname, "unique_id": id})
    
        newList = []
        for group in result:
            if group["_id"] != newid: 
                timestamp = group["timestamp"]
                dt_object = datetime.fromtimestamp(timestamp)
                formatted_datetime = dt_object.strftime("%d-%b-%y %I:%M %p")
                group["dateTime"] = formatted_datetime
                newList.append(group)

    return jsonify({'htmlresponse': render_template('dashboard/oldNotes.html',oldNotesList = newList)})
    