#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class CheckCurConnCount(BaseItem):
    def __init__(self):
        super(CheckCurConnCount, self).__init__(self.__class__.__name__)

    def doCheck(self):
        sqlcmd1 = "show max_connections;"
        sqlcmd2 = "SELECT count(*) FROM pg_catalog.pg_stat_activity;"
        self.result.raw = sqlcmd1 + sqlcmd2
        output1 = SharedFuncs.runSqlCmd(sqlcmd1, self.user, "", self.port, self.tmpPath, "postgres", self.mpprcFile)
        output2 = SharedFuncs.runSqlCmd(sqlcmd2, self.user, "", self.port, self.tmpPath, "postgres", self.mpprcFile)
        if not (output1.isdigit() and output2.isdigit()):
            self.result.rst = ResultStatus.ERROR
            self.result.val = "max_connections: %s\nCurConnCount: %s" % (output1, output2)
        maxConnections = float(output1)
        usedConnections = float(output2)
        if maxConnections > 0 and usedConnections > 0:
            try:
                OccupancyRate = (usedConnections / maxConnections)
            except ZeroDivisionError as ex:
                raise Exception("Can't divide by zero!") from ex
            self.result.val = "%.2f%%" % (OccupancyRate * 100)
            if OccupancyRate < 0.9:
                self.result.rst = ResultStatus.OK
            else:
                self.result.rst = ResultStatus.NG
        else:
            self.result.rst = ResultStatus.ERROR
            self.result.val = "max_connections: %s\nCurConnCount: %s" % (maxConnections, usedConnections)
