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

systemviewModal = Blueprint('systemviewModal',__name__)


mongoCollection = MongoCollections()


@systemviewModal.route("/uptime",methods=['GET','POST'])
def uptime():
    System = {}
    Apache = {}
    Mongo = {}
    Tomcat = {}
    news = {}
    rams = {}
    physical = {}
    moreDetails = {}
    if request.method == 'POST':
        fqdn = request.form['userid']
        cloudName = request.form['res']
        print(fqdn)
        print(cloudName)
        print("I am printing the line")
        uptimeDetails = mongoCollection.getDistictSystemNameInCloud(cloudName,fqdn)
        print(uptimeDetails)
        print("------------------------------------------------------------------------")
        lastUpdatedtime = uptimeDetails.get('Date & Time ')
        DatetimeModel = DateTime(lastUpdatedtime)
        
        try:
            Mongo.update({'Mongo Version':[uptimeDetails.get('Mongo Version')]})
            print(uptimeDetails.get('Mongo Version'))
        except Exception:
            Mongo.update({'Mongo Version':["0"]})

        try:
            lastMongoUpdate = uptimeDetails.get('lastMongoUpdate')
            if mongoLastBackup is not None or mongoLastBackup != "N/A" or mongoLastBackup != "0" or mongoLastBackup != 0:
                mongoRestartTime = DatetimeModel.getChangeTimeFormatHavingIST(lastMongoUpdate)
                mongoLastBackupColor = DatetimeModel.compareDateWithDays(lastUpdatedFormat,mongoRestartTime,3)
            else:
                print("I am in the line 2460")
                mongoLastBackupColor = "red"
            Mongo.update({'Mongo Last Backup':[uptimeDetails.get('lastMongoUpdate'),mongoLastBackupColor]})
        except Exception:
            mongoLastBackupColor = "red"
            print("I am in the line Exceptiom")
            Mongo.update({'Mongo Last Backup':["N/A",mongoLastBackupColor]})


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

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

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

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

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

        try:
            wiretigerSize = uptimeDetails.get('WireTigerSize')
            gb_value = wireTigerConvert(wiretigerSize)
            colorStatus = wireTigerConvertColorStatus(wiretigerSize)
            Mongo.update({'WiredTiger cache space':[gb_value,colorStatus]})
        except Exception as e:

            Mongo.update({'WiredTiger cache space':["N/A","red"]})


        try:
            Tomcat.update({'Incoming Thread Set':[uptimeDetails.get('IncomingThread')]})
        except Exception:
            Tomcat.update({'Incoming Thread Set':["0"]})
        
        try:
            Tomcat.update({'Incoming Utilized':[uptimeDetails.get('IncomingUtilized')]})
        except Exception:
            Tomcat.update({'Incoming Utilized':["0"]})
        

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

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

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

        print("Line 163")


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


        try:
            parabluDiskSize = uptimeDetails.get('parabluSize')
            if parabluDiskSize is not None:
                parabluDiskBytes = convertToBytes(parabluDiskSize)
            else:
                parabluDiskBytes = convert_to_bytes2(uptimeDetails.get('Total Space'))
        except Exception:
            parabluDiskBytes = 0
            parabluDiskSize = "N/A"


        print("The value of the parablu disk size is : ")
        print(parabluDiskBytes)
        print(parabluDiskSize)


        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(uptimeDetails.get('Total Space'))
        except:
            parabluDiskBytes = 0
            

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


        print("This is line 213")


        try:
            parabluDisk = uptimeDetails.get('parabluDiskAvailable')+"B"
            if parabluDisk == "0B":
                parabluDisk = "N/A"
        except Exception as e:
            print(e)
            parabluDisk = "N/A"
        
        moreDetails.update({'/parablu Available':[parabluDisk]})


        try:
            Mongo.update({'Mongo Backup Folder Size':[uptimeDetails.get('MongoBackupFolder')+"B"]})
        except Exception as e:
            print(e)
            Mongo.update({'Mongo Backup Folder Size':["0"+"B"]})

        nightlyRestart = "N/A"
        nightlyRestartStatus = "red"
        try:
            nightlyRestart = uptimeDetails.get('lastNightlyRestart')
            if nightlyRestart is not None or nightlyRestart != "N/A" or nightlyRestart != "0" or nightlyRestart != 0:
                nightlyRestartTime = DatetimeModel.getChangeTimeFormatHavingIST(nightlyRestart)
                nightlyRestartStatus = DatetimeModel.compareDateWithDays(lastUpdatedFormat,nightlyRestartTime,1)
            else:
                nightlyRestartStatus = "red"

        except Exception as e:
            print("Exception : ")
            print(e)

        moreDetails.update({'Nightly Restart':[nightlyRestart,nightlyRestartStatus]})

        
        print("Line number............249")


        try:
            uploadFolder = uptimeDetails.get('UploadFolder')+"B"
            uploadFolderBytes = convert_to_bytes(uptimeDetails.get('UploadFolder'))
            
        except Exception:
            uploadFolderBytes = 0
            uploadFolder = "N/A"

        try:
            percentageuploadFolder= (int(uploadFolderBytes) * 100)/int(parabluDiskBytes)
        except:
            percentageuploadFolder = 0

        if(percentageuploadFolder < 35):
            uploadFolderColor = "darkgreen"
        else:
            uploadFolderColor = "red"

        uploadFolderName = "/parablu"+"/"+cloudName+"/upload"

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


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

        try:
            tmpChunkFolder = uptimeDetails.get('tmpFolder')+"B"
            tmpChunkFolderBytes = convert_to_bytes(uptimeDetails.get('tmpFolder'))
        except Exception:
            tmpChunkFolderBytes = 0
            tmpChunkFolder = "N/A"


        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]})

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

        fFolderSizename = "/parablu"+"/"+cloudName+"/f"

        if(fFolderSizeBytes <= 8192):
            fFolderSizeColor = "darkgreen"
        else:
            fFolderSizeColor = "red"


        moreDetails.update({fFolderSizename:[fFolderSize,fFolderSizeColor,cloudName]})


        try:
            physical.update({'RAM':[uptimeDetails.get('Total Physical Memory')]})
            totalRam = uptimeDetails.get('Total Physical Memory')
        except Exception:
            physical.update({'RAM':["0"]})


        try:
            usedPhyMem = uptimeDetails.get('Used Physical Memory')
            if((totalRam != "-" or totalRam is not None or totalRam != "N/A") and (usedPhyMem != "-" or usedPhyMem is not None or usedPhyMem != "N/A")):
                try:
                    finalPercentage = (int(usedPhyMem) * 100)/int(totalRam)
                except Exception as e:
                    print(e)
                    finalPercentage = 0

                if finalPercentage > 90:
                    phyStatus = "red"
                else:
                    phyStatus = "green"
            
            else:
                physicalMemory = "N/A"
                phyStatus = "red"

            physical.update({'Used RAM':[uptimeDetails.get('Used Physical Memory'),phyStatus]})
        except Exception as e:
            print(e)
            physical.update({'Used RAM':["N/A","red"]})
        

        try:
            physical.update({'Free RAM':[uptimeDetails.get('Free Physical Memory')]})
        except Exception:
            physical.update({'Free RAM':["N/A"]})


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

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

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


        try:
            totalSpace = convert_to_bytes2(uptimeDetails.get('Total Space'))
            physical.update({'Disk Space':[uptimeDetails.get('Total Space')]})
        except Exception:
            totalSpace = 0
            physical.update({'Disk Space':["N/A"]})
        
        try:
            freeSpace = convert_to_bytes2(uptimeDetails.get('Free Space'))
            physical.update({'Disk Free':[uptimeDetails.get('Free Space')]})
        except Exception:
            freeSpace = 0
            physical.update({'Disk Free':["N/A"]})


        try:
            UsedSpace = convert_to_bytes2(uptimeDetails.get('Usable Space'))
            UsedSpacePercentage = (int(UsedSpace) * 100) / int(totalSpace)
            physical.update({'Disk Used':[uptimeDetails.get('Usable Space') ,UsedSpacePercentage]})
        except Exception as e:
            print(e)
            physical.update({'Disk Used':["N/A" ,0]})

        try:
            swapSpace = uptimeDetails.get('Swap Memory / Disabled')
            if(int(swapSpace) > int(totalRam) * 2):
                swapColor = "green"
            else:
                swapColor = "red"
            physical.update({'Swap Space':[uptimeDetails.get('Swap Memory / Disabled'),swapColor]})
        except Exception:
            swapSpace = 0
            physical.update({'Swap Space':["N/A"]})

        try:
            rateLimiter = uptimeDetails.get('rateLimiter')
            if rateLimiter is not None:
                physical.update({'Mongo Rate Limit':[int(float(rateLimiter))]})
            else:
                physical.update({'Mongo Rate Limit':["10 (Default)"]})
        except Exception:
            physical.update({'Mongo Rate Limit':["10 (Default)"]})


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


        try:
            Mongo.update({'Mongo Cap Size':[uptimeDetails.get('MongoCapValue')]})
        except Exception:
            Mongo.update({'Mongo Cap Size':["N/A"]})
        

        try:
            patchfileSize = uptimeDetails.get('patchFileSize')+"B"
            patchfileSizeBytes = convert_to_bytes(uptimeDetails.get('patchFileSize'))
        except Exception as e:
            print(e)
            patchfileSize = "0"
            patchfileSizeBytes = 0


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


        patchFolderSize = "/installables/patch"

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


        syncFolderName = "/parablu"+"/"+cloudName+"/sync-upload"
        try:
            syncFolder = uptimeDetails.get('SyncFolderSize') +"B"
            syncFolderBytes = convert_to_bytes(uptimeDetails.get('SyncFolderSize'))
        except Exception:
            syncFolder = "0"
            syncFolderBytes = 0
        
        if(syncFolderBytes <= 8192):
            syncFolderBytesColor = "darkgreen"
        else:
            syncFolderBytesColor = "red"


        
        moreDetails.update({syncFolderName:[syncFolder,syncFolderBytesColor]})
        try:
            backupPolicy = uptimeDetails.get('BackupPolicy')
        except Exception:
            backupPolicy = "N/A"

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

        try:
            if(int(str(uptimeDetails.get('outgoingUtilized'))) < 0 ):
                print(int(str(uptimeDetails.get('OutgoingThread'))))
                Tomcat.update({'Outgoing Utilized':["0"]})
            else:
                Tomcat.update({'Outgoing Utilized':[uptimeDetails.get('outgoingUtilized')]})
        except Exception as e:
            print(e)
            Tomcat.update({'Outgoing Utilized':["N/A"]})


        try:
            uploadFileSizeLimit = uptimeDetails.get('uploadFileSizeLimitInMB')
            if(int(uploadFileSizeLimit) < 5):
                uploadFileSizeLimitColor = "darkgreen"
            else:
                uploadFileSizeLimitColor = "red"
            Tomcat.update({'Upload File Size Limit':[uptimeDetails.get('uploadFileSizeLimitInMB') + "MB",uploadFileSizeLimitColor]})
        except Exception as e:
            print(e)
            Tomcat.update({'Upload File Size Limit':["N/A"]})


        try:
            Tomcat.update({'Memory Partition Tomcat JOB1':[uptimeDetails.get('MemoryPartTomjob') + "MB"]})
        except Exception as e:
            print(e)
            Tomcat.update({'Memory Partition Tomcat JOB1':["N/A"]})
        
        try:
            Tomcat.update({'Memory Partition Tomcat PCB1':[uptimeDetails.get('MemoryPartTompcb') + "MB"]})
        except Exception as e:
            print(e)
            Tomcat.update({'Memory Partition Tomcat PCB1':["N/A"]})


        print("............Line number 303")



        try:
            news.update({'Blukrypt Status':[uptimeDetails.get('BlukryptStatus')]})
        except Exception:
            news.update({'Blukrypt Status':["N/A"]})

        try:
            news.update({'Number of 429 in outgoing':[uptimeDetails.get('Grep429')]})
        except Exception:
            news.update({'Number of 429 in outgoing':["N/A"]})


        print("line 534")

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