from ...Dependencies.Utilities.util import *
from ...Dependencies.MongoConnection.mongoConnect import *
from ...Dependencies.SSLConfig.sslInfo  import *
from .Modals.DateTime import *
from ...Dependencies.Filters.supportMethods import *

# from .variables import *

systemviewRoute = Blueprint('systemviewRoute',__name__)

@systemviewRoute.route("/systemViewtest")
def systemviewtest():
    return "systemviewtest View Tested"


@systemviewRoute.route("/dashboardsssss/<string:client>")
def systemviewMain(client):
    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)
    cloudDistinct = MongoCollectionInstance.getCloudMainDetailsByClientDistinct(client)
    machineList = MongoCollectionInstance.getTotalMachineList(client)
    dashboardColor =  MongoCollectionInstance.getDashboardStatusByClient(client)

    print("...........................The below is the cloud distinct")
    print(cloudDistinct)
    print(".......The distinct cloud values")

    systemNameList = []

    try:
        finalMachineList = machineList.get("MachinesList")
    except Exception as e:
        print(e)
        print(".............Exception")
        finalMachineList = []


    if finalMachineList is not None and len(finalMachineList) > 0:
        cloudDistinct = finalMachineList

    insideListCursor = []

    for systemName in cloudDistinct:
        print(systemName)
        print(".....................")
        systemDetails = MongoCollectionInstance.getCloudMainDetailsByFqdn(systemName,client)
        print(systemDetails)

        serverType = systemDetails.get('ServerType')
        ServerTypeValue = int(float(serverType))
        systemDetails.update({'MachineTypeValue':ServerTypeValue})

        #Calculating the percentages of the Physical Memory
        TotalPhy = systemDetails.get('Total Physical Memory')
        UsedPhy = systemDetails.get('Used Physical Memory')
        Freephy = systemDetails.get('Free Physical Memory')


        Available = systemDetails.get('Available')


        try:
            availablePercentage = (100 * int(Available))/ int(TotalPhy)
        except Exception as e:

            availablePercentage = 0


        finalAvailablePercentage = 100 - availablePercentage
        systemDetails.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 = systemDetails.get('Total Space')
        UsableSys = systemDetails.get('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
        systemDetails.update({"usedPhyColor":usedPhyColor})
        systemDetails.update({"UsedPercentage":UsedPercentage})
        systemDetails.update({"Freepercentage":Freepercentage})
        systemDetails.update({"UsablePercentage":UsablePercentage})


        swapSpace = systemDetails.get('Swap Memory / Disabled')


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

        systemDetails.update({"swapSpaceColor":swapSpaceColor})

        lastUpdatedtime = systemDetails.get('Date & Time ')
        DatetimeModel = DateTime(lastUpdatedtime)   

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

        lastUpdatedFormat = DatetimeModel.getchangeTimeFormatByDate()

        try:
            nightlyRestart = systemDetails.get('lastNightlyRestart')
            if nightlyRestart is not None or nightlyRestart != "N/A" or nightlyRestart != "0" or nightlyRestart != 0:
                nightlyRestartTime = DatetimeModel.getChangeTimeFormatHavingIST(nightlyRestart)
                #Check the Expiration
                nightlyRestartStatus = DatetimeModel.compareDateWithDays(lastUpdatedFormat,nightlyRestartTime,1)
            else:
                nightlyRestartStatus = "red"
            systemDetails.update({"nightlyRestartColor":nightlyRestartStatus})

        except Exception as e:
            systemDetails.update({"nightlyRestartColor":"red"})
            print("Exception : ")
            print(e)

    
        try:
            parabluSize = systemDetails.get('parabluSize')
            parabluSizeBytes = 0
            if parabluSize is not None or parabluSize != "N/A":
                parabluSizeOutput = convertToBytes(parabluSize)
                print(parabluSizeOutput)
                print("...................This is line 151")
                print(parabluSizeOutput[0])
                parabluSizeBytes = parabluSizeOutput[0]
                systemDetails.update({"parabluSizeSystem":parabluSizeOutput[1]})
            else:
                parabluSize = "N/A"
                systemDetails.update({"parabluSizeSystem":parabluSize})
        except Exception as e:
            print(e)
            systemDetails.update({"parabluSizeSystem":"N/A"})


        try:
            parabluUsed = systemDetails.get('parabluUsed')
            if parabluUsed is not None or parabluUsed != "N/A":
                parabluUsedOutput = convertToBytes(parabluUsed)
                parabluUsedBytes = parabluUsedOutput[0]
                print(parabluUsedBytes)
                systemDetails.update({"parabluUsedSystem":parabluUsedBytes[1]})
            else:
                systemDetails.update({"parabluUsedSystem":"N/A"})
        except Exception as e:
            print(e)
            systemDetails.update({"parabluUsedSystem":"N/A"})
        
        percentageUserdBytes = 0
        try:
            percentageUserdBytes = calculatePercentage(parabluUsedBytes,parabluSizeBytes)
        except Exception as e:
            percentageUserdBytes = 0


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


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


        try:
            parabluAvailable = systemDetails.get('parabluDiskAvailable')
            if parabluAvailable is not None or parabluAvailable != "N/A":
                parabluAvailOutput = convertToBytes(parabluAvailable)
                parabluAvailBytes = parabluUsedOutput[0]
                print(".................Parablu Available")
                print(parabluAvailBytes)
                print(".................Parablu Available")
                systemDetails.update({"parabluDiskAvailableSize":parabluAvailOutput[1]})
            else:
                systemDetails.update({"parabluDiskAvailableSize":"N/A"})

        except Exception as e:
            print(e)
            systemDetails.update({"parabluDiskAvailableSize":"N/A"})


        try:
            percentageAvailable = (100 *parabluAvailBytes)/parabluSizeBytes
            print(percentageAvailable)
            print(".................percentage available ")
        except Exception as e:
            print(e)
            percentageAvailable = 0

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


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

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

            else:
                mongoRestartStatus = "red"
            

            systemDetails.update({"lastMongoUpdateColor":mongoRestartStatus})

        except Exception as e:
            j.update({"lastMongoUpdateColor":"red"})


        insideListCursor.append(systemDetails)


    print(dashboardColor)
    print("..............This is the dashbooardx color")

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