from ...Dependencies.Utilities.util import *
from ...Dependencies.MongoConnection.mongoConnect import *
from ...Dependencies.SSLConfig.sslInfo  import *
from ..variables import *

application = Blueprint('application',__name__)

@application.route("/applicationTest")
def applicationTest():
    return "Application View Tested"


@application.route("/dashboard/<string:client>")
def applicationView(client):
    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"))

    UserTotalDetails = MongoCollectionInstance.getUserTotalByClient(client)
    ColorCollectionDetails = MongoCollectionInstance.getColorCollectionByClient(client)
    cloudNameDetails = MongoCollectionInstance.getCloudNameDetails(client)
    cloudCollection = MongoCollectionInstance.getCloudMainDetailsByClient(client)
    dataProcCollection = MongoCollectionInstance.getDataProtectionByClient(client)
    AgentCollection = MongoCollectionInstance.getAgentVersionByClient(client)
    LicenseAdditionalCollection = MongoCollectionInstance.getLicenseAdditionalByClient(client)
    BackupPolicyData = MongoCollectionInstance.getBackupPolicyDataCollection(client)
    oneDriveMixedUsers = MongoCollectionInstance.getOneDriveMixedUsers(client)

    print(LicenseAdditionalCollection)
    print("................The is licenseAdditional")



    print("This is the Backup Policy Data")
    print(BackupPolicyData)

    try:
        active_users = int(float(UserTotalDetails.get('Active Users')))
        print(active_users)
    except Exception as e:
        print(e)
        print("..............Exception")
        active_users = 0


    try:
        fullBackupCompleted = int(dataProcCollection.get("fullbackupCompleted").replace(",",""))
        atleastOneDevice = int(dataProcCollection.get("atleastOneDevice").replace(",",""))
        activeUsersNum = int(dataProcCollection.get("activeUsers").replace(",",""))

    except Exception as e:
        print(e)
        print("................The above is the exception")
        fullBackupCompleted = 0
        activeUsersNum = "N/A"


    dashboardDetails.update({'Active Users':[activeUsersNum,100]})
    dataProctection.update({'No. of Active Users':[activeUsersNum,100]})


    print(dashboardDetails)
    print(dataProctection)


    try:
        nosofBks = int(float(UserTotalDetails.get('Nos of BK\'s')))
    except Exception as e:
        print(e)
        nosofBks = 0    


    print(nosofBks)
    dashboardDetails.update({'Number of Blukrypts':[nosofBks]})

    try:
        active_user_with = UserTotalDetails.get('Active_user_with_device')
        final_active = active_user_with.replace(",", "")

    except Exception:
        final_active = 0


    activeWithDevice = int(float(final_active))

    try:
        percentageactiveDevice = (activeWithDevice * 100)/activeUsersNum
    except ZeroDivisionError:
        percentageactiveDevice = 0


    dataProctection.update({'Users with at least one device assigned':[activeWithDevice,percentageactiveDevice]})

    try:
        activeNodevice = int(float(UserTotalDetails.get('Active_user_with_nodevice')))
    except Exception:
        activeNodevice = 0


    try:
        percentageactiveNoDevice = (activeNodevice * 100)/activeUsersNum
    except ZeroDivisionError:
        percentageactiveNoDevice = 0


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


    try:
        restoreAttempts = int(float(active_data.get('Restore Attempts')))
    except Exception:
        restoreAttempts = 0


    dashboardDetails.update({'Number of Restore Attempts (Last 30 days)':[restoreAttempts]})

    try:
        currentlyRunningBackupCount = dataProcCollection.get("currentlyRunningBackupCount")
        totalStorageUtilized = dataProcCollection.get("totalStorageUtilized")
        totalActualStorageUtilized = dataProcCollection.get("totalActualStorageUtilized")

        try:
            
            AADTokenExpiry = dataProcCollection.get("AADTokenExpiry")
            if AADTokenExpiry is not None:
                if AADTokenExpiry == "317":
                    AADTokenExpiryColor = "red"
                    AADExpiredOrNot = "Expired"
                elif AADTokenExpiry == "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:
            AADTokenExpiryColor = "red"
            AADExpiredOrNot = "N/A"

    except Exception as e:
        currentlyRunningBackupCount = "N/A"
        totalStorageUtilized = "N/A"
        totalActualStorageUtilized = "N/A"
        AADExpiredOrNot = "N/A"


    
    dashboardDetails.update({'Currently Running Backups':[currentlyRunningBackupCount]})  
    dashboardDetails.update({'Total Storage Utilized':[totalStorageUtilized]})    
    dashboardDetails.update({'Actual Storage Utilized':[totalActualStorageUtilized]})

    print("The below is the duration")
    print(getCertificateDuration(client,10,4))
    print("The above is the duration")


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



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

    try:
        scorecardHeard = ColorCollectionDetails.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


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

    try:
        device_proc = ColorCollectionDetails.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

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

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

    try:
        serverVersion = UserTotalDetails.get('serverVersion')
    except Exception:
        serverVersion = 0


    dashboardDetails.update({"Server Version":[serverVersion]})

    try:
        
        if(AgentCollection is not None):
            try:
                serviceVersion = AgentCollection.get('service')
            except Exception:
                serviceVersion = "service|-"

            if serviceVersion is not None:
                serviceSplit = serviceVersion.split('|')
                dashboardDetails.update({"Agent Version: Windows":[serviceSplit[1]]})
            else:
                dashboardDetails.update({"Agent Version: Windows":"-"})
        else:
            dashboardDetails.update({"Agent Version: Windows":"-"})


        if(AgentCollection is not None):
            try:
                macVersion = AgentCollection.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])
                dashboardDetails.update({"Agent Version: Mac":[macSplit[1]]})
            else:
                dashboardDetails.update({"Agent Version: Mac":"-"})
        else:
            dashboardDetails.update({"Agent Version: Mac":"-"})

    except Exception as e:
        print(e)
        dashboardDetails.update({"Agent Version: Mac":"-"})
        dashboardDetails.update({"Agent Version: Windows":"-"})
    
    try:
        durationColor = "darkgreen"
        if int(duration) <= 7:
            durationColor = "red"
        dashboardDetails.update({'SSL Certificate Valid Until':[sslExper,durationColor,"Days to expire"]})
    except:
        dashboardDetails.update({'SSL Certificate Valid Until':["N/A","N/A", "Days to expire"]})


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

    try:
        LicenceArray = licenceAditional.get('LicenceAdditional')
    except Exception:
        LicenceArray = []


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

    try:
        if BackupPolicyData is not None:
            backupPolicies = BackupPolicyData.get("backupPolicyList")
        else:
            dashboardDetails.update({'Dedup Backup Policy':["N/A","red"]})  


    except Exception as e:
        print(e)
        dashboardDetails.update({'Dedup Backup Policy':["N/A","red"]})

    try:
        dedupBackupPolName = cloudCollection.get("BackupPolicy")
    except Exception as e:
        dedupBackupPolName = "N/A"
    

    try:
        if len(backupPolicies) != 0:
            totalNumber = str(len(backupPolicies)) + " Policies"
            dashboardDetails.update({'Dedup Backup Policy':[totalNumber +" "+ dedupBackupPolName,"red"]})  
        else:
            dashboardDetails.update({'Dedup Backup Policy':["No Policies","red"]})  
    except Exception as e:
        dashboardDetails.update({'Dedup Backup Policy':["No Policies","red"]})  

    try:
        storageTypeInMachine = UserTotalDetails.get("StorageType")
        print(storageTypeInMachine)
    except Exception as e:
        print(e)
        storageTypeInMachine = 0

    print("..............This is line 304 ")

    print("The list of only licence additional is : ")
    try:
        licenceEnabled = LicenseAdditionalCollection.get("LicenceAdditional")
    except Exception as e:
        print(e)
        licenceEnabled = []
    print(licenceEnabled)
    print("--------------------------THIS IS LINE 323")


    print(licenceEnabled)

    value = False

    if "ODB Enabled" in licenceEnabled:
        storage.update({'Storage Target':["OneDrive"]})
        if dataProcCollection is not None:
            typeOfOdbDetails = dataProcCollection.get('MUX-MIX')
            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:
                if(ColorCollectionDetails.get('MuxType')):
                    value = ColorCollectionDetails.get('MuxType')    
                else:
                    value = ColorCollectionDetails.get('MuxType')

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

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


    elif "gdstorage" == storageTypeInMachine:
        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"]})
    
    print("................The percentage of full backup")


    uniqueIdLength = 0
    muxFileUserSize = 0
    if(value):   
        MuxType = "Mux"
        addCloudPrefixMux = "cloud_"+client+"mux"
        muxCollectionByCloud = MongoCollectionInstance.getMuxCollectionByCloud(client)

        print(muxCollectionByCloud)
        unique_odbLoginIds = muxCollectionByCloud.distinct('odbLoginId')

        muxBucketList = MongoCollectionInstance.getMuxBucketList(client)
        if(muxBucketList is not None and len(muxBucketList)>0):
            unique_odbLoginIds = muxBucketList
        uniqueIdLength = len(unique_odbLoginIds)
        uniqueCount = 0


        for odbLoginId in unique_odbLoginIds:
            if uniqueCount >= 10:
                break
            document= MongoCollectionInstance.getMuxCollectionDetailsByBucket(client,odbLoginId)
            if document:
                distinct_documents.append(document)
                uniqueCount = uniqueCount + 1
        

        bucketsCount = len(distinct_documents)

        storage.update({'Total Storage buckets :':[bucketsCount]})
        storage.update({'usersMux':"Click here"})

        muxUsersList = MongoCollectionInstance.getMuxUsersList(client)
        print(muxUsersList)

        
        if muxUsersList is not None:
            try:
                muxFileUserSize = len(muxUsersList)
            except KeyError:
                muxFileUserSize = 0   
        else:
            muxFileUserSize = 0  
    else:
        MuxType = "Non-Mux"


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

    return render_template("dashboard/applicationView.html",uniqueIdLength = uniqueIdLength,active_data = dashboardDetails,MuxDetails = distinct_documents,MuxType=MuxType,store = storage,cloudName = client,activeDevice = activeWithDevice,activeNodevice=activeNodevice,fullBackupNot = fullBackupNot,fullBackup = fullBackup,device = dataProctection,client = client,muxFileUserSize = muxFileUserSize)



@application.route('/get_info', methods=['POST'])
def get_info():
    selection = request.form['selection']
    cloudName = request.form['cloudname']
    print("The below is the CloudName")
    print(cloudName)
    print(selection)

    unique_odbLoginIds = MongoCollectionInstance.getDistinctOdbLoginByClient(cloudName)
    distinct_documents = []
    for odbLoginId in unique_odbLoginIds:
        document= MongoCollectionInstance.getMuxCollectionDetailsByBucket(cloudName,odbLoginId)
        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')

@application.route("/showUsers",methods=['GET','POST'])
def showUsers():
    if request.method == 'POST':
        userid = request.form['userid']
        LicenceArray= MongoCollectionInstance.getMuxUsersList(userid)
    return jsonify({'htmlresponse': render_template('dashboard/muxUser.html',LicenceDetails = LicenceArray)})


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


@application.route("/activeUsers",methods=['GET','POST'])
def activeModal():
    ActiveModal= {}
    if request.method == 'POST':
        cloudName = request.form['userid']
        UserTotalDetails = MongoCollectionInstance.getUserTotalByClient(cloudName)
        print(cloudName)
        try:
            active_users = int(float(UserTotalDetails.get('Active Users')))
        except Exception as e:
            print(e)
            active_users = 0

        print(active_users)
        ActiveModal.update({'Active Users':[active_users,100]})


        try:
            blockListUsersList = MongoCollectionInstance.getBlockedUsersListByCloud(cloudName)
        except Exception as e:
            print(e)
            blockListUsersList = []
        
        ActiveModal.update({"Blocked Users":[len(blockListUsersList)]})
        blockedUserLength = len(blockListUsersList)



        try:
            softBlockedUsersList = MongoCollectionInstance.getSoftBlockedUsersList(cloudName)
        except Exception as e:
            print(e)
            softBlockedUsersList = []
            
        
        ActiveModal.update({"SoftBlock Users":[len(softBlockedUsersList)]})
        softBlockedUsersLength = len(softBlockedUsersList)

        try:
            deletedUsersList = MongoCollectionInstance.getDeletedUsersList(cloudName)
        except Exception as e:
            print(e)
            deletedUsersList = []

        ActiveModal.update({"Deleted Users":[len(deletedUsersList)]})
        deletedUsersListLength = len(deletedUsersList)

    return jsonify({'htmlresponse': render_template('dashboard/activeUsers.html',cloudNe = cloudName,Del_len=deletedUsersListLength,blkLength =blockedUserLength,softLen=softBlockedUsersLength,user = cloudName,employeelist = ActiveModal)})



@application.route("/SoftUsers",methods=['GET','POST'])
def SoftUsers():
    if request.method == 'POST':
        cloudName = request.form['userid']
        print("I am printing the cloud name")
        print(cloudName)
        sof_tBLok_Lis = MongoCollectionInstance.getSoftBlockedUsersList(cloudName)
    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = sof_tBLok_Lis)})



@application.route("/DelUsers",methods=['GET','POST'])
def delUsers():
    if request.method == 'POST':
        cloudName = request.form['userid']
        deletedUsersList = MongoCollectionInstance.getDeletedUsersList(cloudName)
    return jsonify({'htmlresponse': render_template('dashboard/blackfour.html',black404 = deletedUsersList)})


@application.route("/chooselicenceModal",methods=['GET','POST'])
def chooselicenceModal():
    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"))
            
    details = {}
    if request.method == 'POST':
        cloudName = request.form['userid']
        licenseCollection = MongoCollectionInstance.getLicenseCollectionByCloud(cloudName)
        details.update({'Cloud Name': cloudName})
        nosOfMiniCloud = int(float(licenseCollection.get('noOfMiniCloudsAllowed')))
        print("It is coming to this line 1166")
        details.update({'Total Number of Miniclouds': nosOfMiniCloud})
        cloudSizeAllowed = int(float(licenseCollection.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(licenseCollection.get("noOfSyncUsersAllowed")))
        print("It is coming to this line 1174")
        details.update({'Number of Sync Users allowed': nosOfSyncUsers})
        nosOfBackupUsers = int(float(licenseCollection.get("noOfBackupUsersAllowed")))
        print("It is coming to this line 1177")
        details.update({'Number of Backup Users allowed': nosOfBackupUsers})

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

        nosOfExchange = int(float(licenseCollection.get("noOfExchangeUsersAllowed")))
        print("It is coming to this line 1185")
        details.update({'Number of Exchange Users allowed': nosOfExchange})
        contentSearchEnabled = int(float(licenseCollection.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(licenseCollection.get("versioningEnabled")))
        print("It is coming to this line 1195")
        details.update({'Version Enabling': versionEnabling})
        statusCode = licenseCollection.get("statusCode")
        print("It is coming to this line 1198")
        details.update({'Status Code': statusCode})
        cloudId = int(float(licenseCollection.get("cloudId")))
        print("It is coming to this line 1201")
        details.update({'CloudId': cloudId})
        externalStorage = int(float(licenseCollection.get("externalStorageAllowed")))
        print("It is coming to this line 1204")
        details.update({'External Storage Allowed': externalStorage})
        enableMedia = int(float(licenseCollection.get("enableMedia")))
        print("It is coming to this line 1206")
        details.update({'Enable Media': enableMedia})
        LicenceKeyFileName = licenseCollection.get("licenseKeyFileName")
        print("It is coming to this line 1209")
        details.update({'Licence Key Filename': LicenceKeyFileName})
        print("..........600")

        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(licenseCollection.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(licenseCollection.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(licenseCollection.get("noOfDevicesAllowed")))
        details.update({'Number of Device Allowed': noOfDevicesAllowed})
        allowedDeviceOwnershipPer = int(float(licenseCollection.get("allowedDeviceOwnershipPer")))
        details.update({'Allowed Device Ownership per User': allowedDeviceOwnershipPer})
        noOfUsersAllowed = int(float(licenseCollection.get("noOfUsersAllowed")))
        details.update({'Number of Users Allowed': noOfUsersAllowed})   
        details.update({'License Details': "Click here"})  

        print("................639")
    return jsonify({'htmlresponse': render_template('dashboard/licenceData.html',employeelist = details,cloudName = cloudName)})


