from ...Dependencies.Utilities.util import *
from ...Dependencies.MongoConnection.mongoConnect import *
from ..variables import *
from ...Dependencies.Filters.supportMethods import *
from ..SystemView.Modals.DateTime import *
import time


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

admin = Blueprint('admin',__name__)

now = datetime.now()

@admin.route("/testAdmin")
def testAdmin():
    return "This is the test admin"


@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"))

    data = []
    data = list(auth.find())
    count = len(CloudNameCollection)
    print(data)
    owners = set([d['username'] for d in data if 'username' in d])
    color = "warning"

    dashboardList = []
    for client in CloudNameCollection:
        cloudNameDetails = MongoCollectionInstance.getCloudNameDetails(client)
        dashboardList.append(cloudNameDetails)
        my_logger.info("....Client value is "+ client)
        dashboardColorCheck = MongoCollectionInstance.getColorStatusForCloud(client)
        my_logger.info("The value of the dashboard color is "+dashboardColorCheck)
        dashboardColor.update({client:dashboardColorCheck})
        
        CloudOwnerId = cloudNameDetails.get('Owner')
        if CloudOwnerId == "nothing":
            cloudname_to_owner.update({client: "Not Yet Assigned"})
        else:
            userName = MongoCollectionInstance.getAuthDetailsById(CloudOwnerId)
            if userName is None:
                cloudname_to_owner.update({client: "Not Yet Assigned"})
            else:
                print("The username ........."+userName.get('username') )
                cloudname_to_owner.update({
                    client: userName.get('username')
                })


        pipeline = [
            {"$sort": {"_id": -1}},
            {"$group": {"_id": "$CloudName","latest_doc": {"$first": "$$ROOT"}}}
        ]


        finalCursor = MongoCollectionInstance.getCloudMainDetails(client,pipeline)
        print(finalCursor)
        for i in finalCursor:
            cloudname = i['latest_doc']['CloudName']
            print(cloudname)
            datetimeCloud = i['latest_doc']['Date & Time ']
            print(datetimeCloud)

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

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


        CloudUser_Type = cloudNameDetails.get('MachineType')
        if CloudUser_Type is None:
            cloudname_to_type.update({client: "other"})
            print(".........MachineType is None")
        else:
            if CloudUser_Type == "prod":
                cloudname_to_type.update({client: "production"})
                print(".........This is cloudname to type")
                
            cloudname_to_type.update({client: CloudUser_Type})

        
        


    three_hours_ago = datetime.now() - timedelta(hours=3)
    formatted_time = three_hours_ago.strftime("%d %b %Y %H:%M")
   
    my_logger.info(dashboardColor)
    my_logger.info("The above is the dashboard color...........")
    my_logger.info(dashboardList)
    my_logger.info(owners)
    my_logger.info(".................Owners")
    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=dashboardList, owners=owners,counts=count,colorsss = dashboardColor)


@admin.route("/color",methods=['GET','POST'])
def color():
    muxCount = 0
    modalList = {}

    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']
        print("The userid for the ")
        print(userid)
        print("The UserId for the line 1672 is ============================================================================================")
        colorCollection = MongoCollectionInstance.getColorCollectionByClient(userid)
        usertableCollection = MongoCollectionInstance.getUserTotalByClient(userid)
        dataprotectionCollection = MongoCollectionInstance.getDataProtectionByClient(userid)
        licenseAdditionalCollection = MongoCollectionInstance.getLicenseAdditionalByClient(userid)
        
        final_active = 0
        try:
            if usertableCollection is not None:
                active_user_with = usertableCollection.get('Active_user_with_device')
                final_active = active_user_with.replace(",", "")
            else:
                final_active = 0
        except Exception:
            final_active = 0

        try:
            if colorCollection is not None:
                scorecard = colorCollection.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 colorCollection is not None:
                fullBackup = colorCollection.get('usersWithFirstBackup').replace(",","")
            else:
                fullBackup = 0
        except Exception:
            fullBackup = 0

        try:
            if colorCollection is not None:
                ActiveUsers = colorCollection.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 colorCollection is not None:
                MuxType = colorCollection.get('MuxType')
                if MuxType is None:
                    MuxType = 0
            else:
                MuxType = 0
        except Exception:
            MuxType = 0

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

        length202 = len(black202)

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

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


        try:
            if colorCollection is not None:
                device_proc = colorCollection.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 colorCollection is not None:
                oneDrive = colorCollection.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 = []
        
        modalList.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:
            fullBackup = int(dataprotectionCollection.get("fullbackupCompleted").replace(",",""))
            atleastOneUser = int(dataprotectionCollection.get("atleastOneDevice").replace(",",""))
        except:
            fullBackup = 0
        try:
            print("The value at 1848 is ")
            print(atleastOneUser)
            if atleastOneUser != 0:
                percentageFullbackup = (fullBackup * 100) / atleastOneUser 
                print(percentageFullbackup)
            else:
                percentageFullbackup = 0
        except Exception:
            percentageFullbackup = 0


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

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

        modalList.update({"Devices have been protected in the last 30 days":[str(device_value),"Greater than 70%",device_value]})
            
        modalList.update({"Black List 201 Users":[black202,"Should be 0"]})
        
        modalList.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):
            muxValue = []
            muxValue = MongoCollectionInstance.getMuxUsersList(userid)
            if muxValue is not None:
                muxCount = len(muxValue)
            else:
                muxCount = 0
            if muxCount > 0:
                modalList.update({"Users with No Storage Buckets":[muxValue,"Should be 3"]})
        
                
        email_percentages = {}

        try:
            if licenseAdditionalCollection is not None:
                LicenceArray = licenseAdditionalCollection.get('LicenceAdditional')
            else:
                LicenceArray = []
        except Exception as e:
            print(e)
            LicenceArray = []


        print("The line number 1687")
        
        if(len(LicenceArray) > 0):
            print("This is the line 1864")
            if "ODB Enabled" in LicenceArray:
                print("The below is the value of onedrive")
                print("This is insode the ODB ENabled")
                if oneDrive is None:
                    OneDriveSize = 0
                    print("This is OneDriveSize =0")
                    modalList.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)

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

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


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

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

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

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


        try:
            # SystemName = findHostNameWithSystem(userid)
            # print("The value if the SystemName is "+SystemName)

        
            systemDetailsCollection = MongoCollectionInstance.getCloudMainDetailsByClientDocument(userid)
            
            print("The below is the document from the collection")
            print(systemDetailsCollection)
            lastUpdatedtime = systemDetailsCollection.get('Date & Time ')
            DatetimeModel = DateTime(lastUpdatedtime)   

            print(DatetimeModel.lastUpdated)
            print("..........Datetime Modal")

            lastUpdatedFormat = DatetimeModel.getchangeTimeFormatByDate()

            try:
                lastMongoUpdate = systemDetailsCollection.get('lastMongoUpdate')
                if lastMongoUpdate is not None or lastMongoUpdate != "N/A" or lastMongoUpdate != "0" or lastMongoUpdate != 0:
                    mongoRestartTime = DatetimeModel.getChangeTimeFormatHavingIST(lastMongoUpdate)
                    mongoColor = DatetimeModel.compareDateWithDays(lastUpdatedFormat,mongoRestartTime,3)
                else:
                    mongoColor = "red"

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

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


            try:
                nightlyRestart = systemDetailsCollection.get('lastNightlyRestart')
                if nightlyRestart is not None or nightlyRestart != "N/A" or nightlyRestart != "0" or nightlyRestart != 0:
                    nightlyRestartTime = DatetimeModel.getChangeTimeFormatHavingIST(nightlyRestart)
                    #Check the Expiration
                    nightColor = DatetimeModel.compareDateWithDays(lastUpdatedFormat,nightlyRestartTime,1)
                else:
                    nightColor = "red"
                    
                
                modalList.update({"Last Nightly Restart":[nightlyRestart,"Date & Time :",nightColor]})

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


            try:
                physicalMemory = systemDetailsCollection.get("Total Physical Memory")
                usedMemory = systemDetailsCollection.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)
                    print("The value of the total physical memory is : " + physicalMemory)
                    print("The value of the used physical memory is : " + usedMemory)

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


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

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


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


            try:
                WireTigerSize = wireTigerConvert(systemDetailsCollection.get("WireTigerSize"))
                wiretigerColorStatus = wireTigerConvertColorStatus(systemDetailsCollection.get("WireTigerSize"))
                modalList.update({"WiredTiger Cache Size":[WireTigerSize,"Exceeds 20 GB :",wiretigerColorStatus]})


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


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

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



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


            print("=================================Parablu Disk Details===========================================")
            
            
            try:
                parabluDiskSize = "N/A"
                parabluDiskSize = systemDetailsCollection.get('parabluSize')   
                if parabluDiskSize is not None:
                    print("The line number 2384" + parabluDiskSize)
                    print("The line number 2384")
                    parabluDiskBytes = convert_to_bytes(parabluDiskSize)

            except Exception:
                print("The line number 2388")
                parabluDiskBytes = 0
                parabluDiskSize = "N/A"
            
            
            try:
                if parabluMounted == "Not Mounted" or parabluDiskSize == "N/A" or parabluDiskSize is None:
                    print("The line number 2395")
                    parabluDiskBytes = convert_to_bytes2(systemDetailsCollection.get('Total Space'))
                    print("The parablu disk is not mounted so considering / value")
                    print("The vlue oif the / parablu is :")
                    print(parabluDiskBytes)

            except:
                print("The line number 2402")
                parabluDiskBytes = 0

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


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


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

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


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

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



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

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

            except Exception:
                syncFolder = "0"
                syncFolderBytes = 0

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

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

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

            print("===================================LINE 2923==============================================================")

            print(backupPolicy)
            print("===================================LINE 2925==============================================================")

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

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

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

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


            
        
        except Exception as e:
            print(e)
            print("The value of exception is above")
            modalList.update({"Last Mongo Backup on":["N/A","Date&Time :","red"]})
            modalList.update({"Last Nightly Restart on":["N/A","Date&Time :","red"]})
            modalList.update({"Ram Size":["N/A","Exceeded 90% :","red"]})
            modalList.update({"/upload folder size":["N/A","Exceeded 35% :","red"]})
            modalList.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
        print("================================LINE 2973========================================================================")
        print("The value of the User Id is : ")
        print(userid)


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

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

        #         print("The value of the data protectection list is ")
        #         print(dataprocListNew)

        #         if dataprocListNew is not None:
        #             typeOfOdbDetails = dataprocListNew.get('MUX-MIX')
        #             print("The value of yje type of details is ")
        #             print(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):  
        #         print("This value is true")
        #         print("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"
        #         print("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')
        #         print("I am in the line 3052")

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

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





        #         print("============3059==================")

        #     print("the value of buckets which exceeded the 50 percentage is ")
        #     print(uniqueCount)
        # except Exception as e:
        #     print(e)
        #     print("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=modalList,client = userid,muxCount = muxCount,length202=length202,length404=length404,lengthOne = lengthOne)})


@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)
        colorCollection = MongoCollectionInstance.getColorCollectionByClient(userid)
        my_logger.info("The value of the data is")
        my_logger.info(data)
        if colorCollection is not None:
            black202 = colorCollection.get('Black202')
        else:
            black202 = []
        my_logger.info("The Belowis black 202 data")
        my_logger.info(black202)
    return jsonify({'htmlresponse': render_template('dashboard/blacktwo.html',black202 = black202)})


@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)
        colorCollection = MongoCollectionInstance.getColorCollectionByClient(userid)
        
        if colorCollection is not None:
            black404 = colorCollection.get('black404')
        else:
            black404 = []

    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")

        colorCollection = MongoCollectionInstance.getColorCollectionByClient(userid)
        if colorCollection 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)])
        licenseAdditionalCollection = MongoCollectionInstance.getLicenseAdditionalByClient(userid)
        
        if licenseAdditionalCollection is not None:
            LicenceArray = licenseAdditionalCollection.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)


@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:
        muxValue = MongoCollectionInstance.getMuxUsersList(userid)
        print(len(muxValue))
        # for j in black404:
        #     print(j)
    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = muxValue)})


@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("/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("/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)